我目前有billDates
,这是一个非常不一致的日期列表。我想要做的是按月分别列出日期或列表。即如果我有12/30/2015
,1/5/2016
,1/6/2016
,2/5/2016
,我应该有3个列表。
这是我到目前为止所拥有的:
// billDates = list of DateTime
List<List<DateTime>> datesByMonth = new List<List<DateTime>>();
var years = billDates.GroupBy(x => x.Year);
foreach (var year in years)
{
var months = year.GroupBy(x => x.Month);
foreach (var month in months)
{
List<DateTime> datesWithinMonth = new List<DateTime>();
foreach (DateTime dt in month)
{
datesWithinMonth.Add(dt);
}
datesByMonth.Add(datesWithinMonth);
}
}
我的结果将它们分开,但它们都将它们分组错误。我究竟做错了什么?
答案 0 :(得分:3)
尝试按月和年属性对列表进行分组,样本:
var groupResult = billDates.GroupBy(x => new { x.Month, x.Year });
List<List<DateTime>> datesByMonth = groupResult.Select(g => g.ToList())
.ToList();
您必须使用groupResult
方法选择Select
上的每个组,并将其作为列表。最后,只需使用ToList
方法获取所有列表,并获取列表(在您的情况下为datetime)。