tags:

views:

56

answers:

2

Hi,

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

+8  A: 
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
+1  A: 
totalIncome = myList.Sum(c=>
    (c.RecType==1 ? c.Income : 0));
code4life
I believe my code is going to be 15-20% faster than @Mark's...
code4life