c# - 我可以使用 linq 来实现这个 foreach 循环所做的同样的事情吗?

标签 c# linq

这是我的 C# 代码:

private double get806Fees (Loan loan)
{
    Loan.Fee.Items class806;
    foreach (Loan.Fee.Item currentFee in loan.Item.Fees)
    {
        if (currentFee.Classification == 806) class806.Add(currentFee);
    }

    // then down here I will return the sum of all items in class806
}

我可以使用 linq 来做到这一点吗?如果是这样,如何?我从未使用过 linq,我在多个地方读到过使用 linq 而不是 foreach 循环更快...这是真的吗?

最佳答案

类似于一些现有答案,但在查询中进行投影,使 Sum 调用更简单:

var sum = (from fee in loan.Items.Fees
           where fee.Classification == 806
           select fee.SomeValueToSum).Sum();

关于c# - 我可以使用 linq 来实现这个 foreach 循环所做的同样的事情吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1578308/

相关文章:

c# - 根据字符串字段名称选择不同的实体值

c# - Linq 查询 nhibernate;不支持异常

c# - 重组数据排序 C#

c# - 通过类字符串属性过滤

c# - 发送邮件失败,无法连接到远程服务器

c# - 在 linq 查询中使用 string.IsnullorEmpty 的问题

c# - 更改 FileSavePicker 以从独立存储而不是应用程序存储中保存文件。异常 WP8.1

c# - 测试一个值是否包含在 Dictionary<TKey, List<TValue>> 中

c# - WCF 服务作为 MVC 应用程序的一部分

c# - .NET C# 设置由 lambda 选择器定义的字段的值