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
totalIncome = myList.Where(x => x.RecType == 1).Select(x => x.Income).Sum();
First you filter on the record type (Where
); then you transform by Select
ing 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);
totalIncome = myList.Sum(c=> (c.RecType==1 ? c.Income : 0));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With