Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
934 views
in Technique[技术] by (71.8m points)

c# - List Distinct entries based on property and sum of duplicates

Im wondering I may be asking a simple question, but trying to get a elegant solution. I have a situation where below are the rows

State Label Value

  1. Alabama AB 9
  2. Alabama AB 4
  3. Arizona AZ 5
  4. Texas TX 6
  5. Texas TX 15
  6. California CA 14
  7. California CA 11
  8. California CA 2

Considering the above List<ValueLabels> object (each ValueLabel object will have set of State, Label and value), I should generate another list which contains below information.

  1. Alabama AB 13
  2. Arizona AZ 5
  3. Texas TX 21
  4. California CA 27

That mean, eventually, I should get a unique records based on State property and value property should be sum of all duplicate entries based on State property.

I have used ListObj.DistinctBy(p => p.State).ToList() function with lambda expression but I could not add the values to gether.

Can anyone help me in achieving the above? Please let me know if further information is needed.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Not tested, but this should work.

var newList = list.GroupBy(x=> new {x.State , x.Label })
                  .Select(x=> new YourClass(x.Key.State, x.Key.Label, x.Sum(x=>x.Value) ))
                  .ToList();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...