2015-08-22 27 views
1

我有一個Dictionary<DateTime, List<Item>>C#字典<日期時間,列表<Item>>由日期時間(空值)

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<Item>基它每年/月,以便它降序(最新的在前)順序列表然後創建一個字典。

我的問題是:如何OrderByDescending還基於DateTime可空(最新的第一個)字典中的列表?

+0

請參閱:[鏈接](http://stackoverflow.com/questions/8110324/how-to-按鍵排序) –

+0

首先應該是最新的還是第一個應該是null? –

+0

首先應該是最新的,雖然是可爲空的屬性,但沒有空值。總會有一個日期時間值。 – user2818430

回答

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(t => t.Published.GetValueOrDefault()).ToList()); 
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(x => x.Created).ToList());