# 使用LINQ计算表格，星期二等的数量[英] Count number of Mondays, Tuesdays etc from table using Linq

### 问题描述

```Status      StatusDate

DELIVRD     2015-04-16 11:57:47.000

DELIVRD     2015-04-16 13:02:57.000
```

```var mondays = rad.SMSSentItems
.Where(x => (x.StatusDate.Value.DayOfWeek == DayOfWeek.Monday)
&& (x.Status == "DELIVRD"))
.ToList()
.Count;
```

## 推荐答案

```var weekDays = rad.SMSSentItems
.Where(x => x.Status == "DELIVRD")
.AsEnumerable()
.GroupBy(x => x.StatusDate.Value.DayOfWeek)
.Select(g => {
//Total items sent on this day of the week
var totalItemCount = g.Count();
//Total number if this distinct day of the week
var totalNumberOfDays = g.Select(x => x.StatusDate.Value.Date).Distinct().Count();
return new {
DayOfWeek = g.Key,
TotalItemCount = totalItemCount,
TotalNumberOfDays = totalNumberOfDays,
AverageItemPerDay = totalItemCount / totalNumberOfDays
};
})
.ToList();
```

### 问题描述

I'm trying to figure out how to count the number of Mondays, Tuesdays etc in a table using Linq and C#

Here is my sample data:

```Status      StatusDate

DELIVRD     2015-04-16 11:57:47.000

DELIVRD     2015-04-16 13:02:57.000
```

I know I need to use Group by to group the same Mondays, Tuesdays etc as 1.

My attempt:

```var mondays = rad.SMSSentItems
.Where(x => (x.StatusDate.Value.DayOfWeek == DayOfWeek.Monday)
&& (x.Status == "DELIVRD"))
.ToList()
.Count;
```

## 推荐答案

You need to filter by the desired Status (DELIVRD) then group them by DayOfWeek of the status date

```var weekDays = rad.SMSSentItems
.Where(x => x.Status == "DELIVRD")
.AsEnumerable()
.GroupBy(x => x.StatusDate.Value.DayOfWeek)
.Select(g => {
//Total items sent on this day of the week
var totalItemCount = g.Count();
//Total number if this distinct day of the week
var totalNumberOfDays = g.Select(x => x.StatusDate.Value.Date).Distinct().Count();
return new {
DayOfWeek = g.Key,
TotalItemCount = totalItemCount,
TotalNumberOfDays = totalNumberOfDays,
AverageItemPerDay = totalItemCount / totalNumberOfDays
};
})
.ToList();
```