0

I have the following class:

public class Data {
  public Decimal DataValueA { get; set; }
  public Decimal DataValueB { get; set; }
  public Decimal DataValueC { get; set; }
  public Decimal DataValueD { get; set; }
} // Data

And I have a List<Data>. I need to create a new Data object:

Data total = new Data();

Where the DataValueA is the sum of all DataValueAs in Data items of List<Data>.

The same for DataValueB, DataValueC, etc.

I was trying to do this with Linq but now sure how.

FishBasketGordo
  • 22,904
  • 4
  • 58
  • 91
Miguel Moura
  • 36,732
  • 85
  • 259
  • 481

3 Answers3

2
var total = new Data
{
    DataValueA = list.Sum(x => x.DataValueA),
    DataValueB = list.Sum(x => x.DataValueB),
    ...
};
James
  • 80,725
  • 18
  • 167
  • 237
1

If multiple enumerations of the collection are OK with you, you could use list.Sum(item => item.Property) several times. If it is critical that you go through the list only once, for example, because it is generated through deferred execution of filters, you could use Aggregate instead:

var totals = list.Aggregate(new Data(), (prev, item) => {
     prev.DataValueA += item.DataValueA;
     prev.DataValueB += item.DataValueB;
     ...
     return prev;
});
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

You could use Sum but that will cause a number of iterations over the list:

var total = new Data
{
    DataValueA = list.Sum(x => x.DataValueA),
    DataValueB = list.Sum(x => x.DataValueB),
    DataValueC = list.Sum(x => x.DataValueC),
    DataValueD = list.Sum(x => x.DataValueD),
};

Or you could us Aggregate which will only iterate the list once:

var data = new[]{
            new Data{DataValueA=1,DataValueB=2,DataValueC=3,DataValueD=4},
            new Data{DataValueA=1,DataValueB=2,DataValueC=3,DataValueD=4},
            new Data{DataValueA=1,DataValueB=2,DataValueC=3,DataValueD=4},
            new Data{DataValueA=1,DataValueB=2,DataValueC=3,DataValueD=4},
        };

var result = data.Aggregate(new Data(),(a,b) => {
    a.DataValueA += b.DataValueA; 
    a.DataValueB += b.DataValueB;
    a.DataValueC += b.DataValueC;
    a.DataValueD += b.DataValueD;
    return a;
});

Live example: http://rextester.com/ODL27846

More info: LINQ Aggregate algorithm explained

Community
  • 1
  • 1
Jamiec
  • 133,658
  • 13
  • 134
  • 193