使用Linq从表中计算星期一,星期二等的数量

时间:2017-12-23 19:24:52

标签: c# linq

我正试图弄清楚如何使用Linq和C#计算星期一,星期二等的数量

以下是我的示例数据:

Status      StatusDate

DELIVRD     2015-04-16 11:57:47.000

DELIVRD     2015-04-16 13:02:57.000

我知道我需要使用Group by将相同的星期一,星期二等分组为1。

我的尝试:

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

1 个答案:

答案 0 :(得分:5)

您需要按所需状态(DELIVRD)进行过滤,然后按状态日期DayOfWeek对其进行分组

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();