List Distinct entries based on property and sum of

2019-02-27 12:25发布

问题:

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.

回答1:

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();


回答2:

On solution is using grouping:

var result = from o in listObj
             group o by o.State into g
             select new ValueLabels() 
             { 
                 State = g.Key, 
                 Label = g.First().Label,
                 Value = g.Sum(i => i.Value)
             };


回答3:

try this :

MyListOfComplextData.GroupBy(r => r.state) .Select(a => new { sum= a.Sum(b => b.code), Name = a.Key}) .ToList();



标签: c# list lambda