Linq和条件和 [英] Linq and conditional sum

查看:66
本文介绍了Linq和条件和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个课程和一个清单,如下:

I have a class and a list as below:

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

List<C1> myList ...;

该列表加载了多个记录,并且它们在RecType中具有各种值 我要计算的是收入"和结果"总计,但仅针对RecType的某个值

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);

如何使用linq完成此操作?

How can I accomplish this with linq?

谢谢

推荐答案

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

首先,您对记录类型(Where)进行过滤;然后通过Select转换每个对象的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.

或更简洁的版本:

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

这篇关于Linq和条件和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆