c#Dictionary< DateTime,List< Item>>


c# Dictionary<DateTime, List<Item>> order list by DateTime (nullable value)

我有一台Dictionary>

1
2
3
4
5
    Dictionary<DateTime, List<Item>> result =
        myList
            .GroupBy(k => new DateTime(k.Created.Value.Year, k.Created.Value.Month, 1))
            .OrderByDescending(k => k.Key)
            .ToDictionary(k => k.Key, v => v.ToList());

这将使一个List每年/每月对其进行分组,然后按降序(最新的第一个)对其进行排序,然后从中创建一个字典。

我的问题是:如何根据日期时间可以为空(最新的第一个)在字典中按降序排序?


我想我明白了:

1
2
3
Dictionary<DateTime, List<Item>> result = myList.GroupBy(k => new DateTime(k.Created.Value.Year, k.Created.Value.Month, 1))
  .OrderByDescending(k => k.Key)
  .ToDictionary(k => k.Key, v => v.OrderByDescending(t => t.Published.GetValueOrDefault()).ToList());

试试这个:

1
2
3
4
5
Dictionary<DateTime, List<Item>> result =
    myList
        .GroupBy(k => new DateTime(k.Created.Value.Year, k.Created.Value.Month, 1))
        .OrderByDescending(k => k.Key)
        .ToDictionary(k => k.Key, v => v.OrderByDescending(x => x.Created).ToList());