【问题标题】:c# Dictionary<DateTime, List<Item>> order list by DateTime (nullable value)c# Dictionary<DateTime, List<Item>> 按日期时间排序列表(可为空值)
【发布时间】:2015-08-22 07:27:20
【问题描述】:

我有一个Dictionary&lt;DateTime, List&lt;Item&gt;&gt;

    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&lt;Item&gt; 每年/每月对其进行分组,按降序排列(最新的优先),然后从中创建一个字典。

我的问题是:如何根据 DateTime 可为空(最新的优先)对字典中的列表进行 OrderByDescending 排序?

【问题讨论】:

  • 请看:link
  • 第一个应该是最新的还是第一个应该为空?
  • 第一个应该是最新的,虽然是一个可为空的属性,但没有空值。总会有一个日期时间值。

标签: c#


【解决方案1】:

我想我明白了:

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());

【讨论】:

    【解决方案2】:

    试试这个:

    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());
    

    【讨论】:

      猜你喜欢
      • 2013-08-06
      • 2013-03-18
      • 1970-01-01
      • 2016-08-09
      • 1970-01-01
      • 2015-11-02
      • 1970-01-01
      • 2017-04-03
      • 1970-01-01
      相关资源
      最近更新 更多