【问题标题】:C# list<item> group by year then by monthC# list<item> 按年分组,然后按月分组
【发布时间】:2015-08-22 16:08:20
【问题描述】:

我有一个 List 并且 Item 包含一个名为 Created 的属性,它是 DateTime。

我怎样才能像这样按年然后按月按降序对项目进行分组?

2015
    August
    July
    June
    May
    April
    March
    February
    January
2014
    December
    November
    October
........

这是我的方法:

var grouped = myList.GroupBy(t => t.Created.Year).Select(t => new { Year = t.Key, Months = t.GroupBy(x => x.Created.Month) });

【问题讨论】:

  • .ThenBy(t =&gt; t.Created.Month)放在GroupBy(t =&gt; t.Created.Year)之后
  • OrderBy(..).ThenBy(..) 无效...
  • 或使用GroupBy(t=&gt;new {t.Created.Year, t.Created.Month})同时分组

标签: c#


【解决方案1】:

不知道是否适合,但我会这样做:

var grouped = myList.GroupBy(t => t.Created.Year)
    .Select(t => new
    {
        Year = t.Key,
        Months = t.GroupBy(x => x.Created.Month)
            .Select(y => new
            {
                Month = y.Key,
                Values = y.ToList()
             })
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多