问题描述
我试图弄清楚如何使用Linq和C#
在表中计算星期一,星期二等的数量这是我的示例数据:
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;
推荐答案
您需要通过所需的状态过滤(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();
问题描述
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();