Linq和条件总和

bza*_*fir 17 linq

我有一个类和一个列表如下:

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

List<C1> myList ...;
Run Code Online (Sandbox Code Playgroud)

该列表加载了几个记录,它们在RecType中有各种值我想要的是计算收入和结果的总数,但仅限于RecType的某个值

这是我需要得到的伪代码

totalIncome = myList.Sum(Income).Where(RecType==1);
Run Code Online (Sandbox Code Playgroud)

我怎样才能用linq实现这个目标?

谢谢

cod*_*ife 31

totalIncome = myList.Sum(c=>
    (c.RecType==1 ? c.Income : 0));


Mar*_*off 27

totalIncome = myList.Where(x => x.RecType == 1).Select(x => x.Income).Sum();
Run Code Online (Sandbox Code Playgroud)

首先你过滤记录类型(Where); 然后,通过变换Select荷兰国际集团的Income每个对象的; 最后你Sum全都了.

或者更简洁的版本:

totalIncome = myList.Where(x => x.RecType == 1).Sum(x => x.Income);
Run Code Online (Sandbox Code Playgroud)