2

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.

Christoph Fink
  • 22,727
  • 9
  • 68
  • 113
Kumar
  • 131
  • 1
  • 11
  • You definitely should group them, and then get the sum. DistictBy is used for getting unique items. – vmeln May 22 '14 at 11:43

3 Answers3

2

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();
Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
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)
             };
Christoph Fink
  • 22,727
  • 9
  • 68
  • 113
1

try this :

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

Royi Namir
  • 144,742
  • 138
  • 468
  • 792