22

I have a class and a list as below:

class C1
{
    int RecType ...;
    decimal Income ...;
    decimal Outcome ...;
}

List<C1> myList ...;

The list is loaded with several records, and they have various values in RecType What I want is to calculate total on Income and Outcome but only for a certain value of RecType

Here's a pseudo code of what I need to get

totalIncome = myList.Sum(Income).Where(RecType==1);

How can I accomplish this with linq?

Thank you

bzamfir
  • 4,698
  • 10
  • 54
  • 89

2 Answers2

46
totalIncome = myList.Where(x => x.RecType == 1).Select(x => x.Income).Sum();

First you filter on the record type (Where); then you transform by Selecting the Income of each object; and finally you Sum it all up.

Or for a slightly more terse version:

totalIncome = myList.Where(x => x.RecType == 1).Sum(x => x.Income);
Mark Rushakoff
  • 249,864
  • 45
  • 407
  • 398
41
totalIncome = myList.Sum(c=>
    (c.RecType==1 ? c.Income : 0));
code4life
  • 15,655
  • 7
  • 50
  • 82