使用LINQ求和属性

时间:2010-06-28 14:14:36

标签: c# linq sum

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;

最后一行语法不正确。是否可以这样做,或者我必须为此属性编写查询以计算总和?

由于

3 个答案:

答案 0 :(得分:2)

btw,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
};

答案 1 :(得分:2)

也许我错过了什么,但这肯定有用。

Count()方法返回int,因此DealsThisMonthOpenDealsThisMonthLostDealsThisMonthWon都是整数值。 DealsThisMonth只是这三个整数值的总和。

你也可以让它更清洁一些(除非你以后需要三个不同的值:

var dealsThisMonth = deals
    .Count(d => d.DateCreated.Month == date.Month
        && (new string[] { "Open", "Lost", "Won" }).Contains(d.DealStatus));

答案 2 :(得分:0)

您是否考虑过扩展方法?您提供总和功能的地方。