Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq and conditional sum

Tags:

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

like image 506
bzamfir Avatar asked Jun 05 '10 01:06

bzamfir


2 Answers

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); 
like image 133
Mark Rushakoff Avatar answered Oct 03 '22 16:10

Mark Rushakoff


totalIncome = myList.Sum(c=>     (c.RecType==1 ? c.Income : 0));
like image 41
code4life Avatar answered Oct 03 '22 17:10

code4life