使用LINQ对属性进行求和[英] Sum properties using LINQ

本文是小编为大家收集整理的关于使用LINQ对属性进行求和的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

DealsThisMonthOpen = deals.Where(deal => deal.DateCreated.Month == date.Month && deal.DealStatus == "Open").Count(),
DealsThisMonthLost = deals.Where(deal => deal.DateCreated.Month == date.Month && deal.DealStatus == "Lost").Count(),
DealsThisMonthWon = deals.Where(deal => deal.DateCreated.Month == date.Month && deal.DealStatus == "Won").Count(),
DealsThisMonth = DealsThisMonthOpen + DealsThisMonthLost + DealsThisMonthWon;

最后一行语法不正确.是否可以这样做,否则我将不得不为此属性编写查询来计算总和?

谢谢

推荐答案

顺便说一句,Count() 也支持 predicate 参数:http://msdn.microsoft.com/en-us/library/bb535181.aspx

所以你可以:

var a = deals.Count(deal => deal.DateCreated.Month == date.Month && deal.DealStatus == "Open"),
var b = deals.Count(deal => deal.DateCreated.Month == date.Month && deal.DealStatus == "Lost"),
var c = deals.Count(deal => deal.DateCreated.Month == date.Month && deal.DealStatus == "Won"),

new foobar
{
    DealsThisMonthOpen = a,
    DealsThisMonthLost = b,
    DealsThisMonthWon = c,
    DealsThisMonth = a + b + c
};

本文地址:https://www.itbaoku.cn/post/1557127.html

问题描述

DealsThisMonthOpen = deals.Where(deal => deal.DateCreated.Month == date.Month && deal.DealStatus == "Open").Count(),
DealsThisMonthLost = deals.Where(deal => deal.DateCreated.Month == date.Month && deal.DealStatus == "Lost").Count(),
DealsThisMonthWon = deals.Where(deal => deal.DateCreated.Month == date.Month && deal.DealStatus == "Won").Count(),
DealsThisMonth = DealsThisMonthOpen + DealsThisMonthLost + DealsThisMonthWon;

The last line is not syntax correct. Is it possible to do it like this or I will have to write query for this Property to calculate sum?

Thanks

推荐答案

btw, Count() also supports predicate argument: http://msdn.microsoft.com/en-us/library/bb535181.aspx

So you can:

var a = deals.Count(deal => deal.DateCreated.Month == date.Month && deal.DealStatus == "Open"),
var b = deals.Count(deal => deal.DateCreated.Month == date.Month && deal.DealStatus == "Lost"),
var c = deals.Count(deal => deal.DateCreated.Month == date.Month && deal.DealStatus == "Won"),

new foobar
{
    DealsThisMonthOpen = a,
    DealsThisMonthLost = b,
    DealsThisMonthWon = c,
    DealsThisMonth = a + b + c
};