将List <datetime>转换为每月和每年分开的列表

时间:2016-05-16 19:51:41

标签: c# linq datetime

我目前有billDates,这是一个非常不一致的日期列表。我想要做的是按月分别列出日期或列表。即如果我有12/30/20151/5/20161/6/20162/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);
    }
}

我的结果将它们分开,但它们都将它们分组错误。我究竟做错了什么?

1 个答案:

答案 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)。