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

### 问题描述

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

## 推荐答案

```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
};
```

### 问题描述

```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
};
```