美好的一天,我有一个列表,有一些日期,我需要得到一周中一天的天数,例如,获取一个int变量星期日的日期数,另一个int星期一.. .
我尝试使用以下代码:
List<int> SundayDates = DateList.FindAll(x => x.DayOfWeek = DayOfWeek.Sunday)
Run Code Online (Sandbox Code Playgroud)
但它说它只读,(和DateList,是我存储我的日期和我想要的地方的列表).
==,即进行相等性检查.单个=是作业int numberOfSundays = DateList.Count(x => x.DayOfWeek == DayOfWeek.Sunday);
Run Code Online (Sandbox Code Playgroud)
这是一周中每一天的计数.分组连接确保即使列表中没有一天(例如星期一没有出现),它仍将出现在结果列表中,计数为0.
var DateList = new List<DateTime>(); // your populated list of dates
var allDaysOfWeek = Enum.GetValues(typeof(DayOfWeek)).Cast<DayOfWeek>();
var totalDayCounts = allDaysOfWeek.GroupJoin(DateList, dayOfWeek => dayOfWeek, date => date.DayOfWeek, (dayOfWeek, times) => new
{
DayOfTheWeek = dayOfWeek,
DayOfWeekCount = times.Count()
});
Run Code Online (Sandbox Code Playgroud)
不要忘记using System.Linq;在代码文件的顶部添加