2015-03-02 39 views
1

我有一個字典列表,我希望它按日期鍵以降序排列。但是下面的查詢給出了不恰當的結果請幫忙。根據C#中的鍵對字典列表排序#

日期格式爲DD/MM/YYYY

List<Dictionary<string, string>> list = new List<Dictionary<string, string>>(); 
      Dictionary<string, string> dict1 = new Dictionary<string, string>(); 
      dict1["Date"] = "01/03/2015"; 
      dict1["Name"] = "bbb"; 
      list.Add(dict1); 

      Dictionary<string, string> dict2 = new Dictionary<string, string>(); 
      dict2["Date"] = "11/08/2014"; 
      dict2["Name"] = "ccc"; 
      list.Add(dict2); 

      Dictionary<string, string> dict3 = new Dictionary<string, string>(); 
      dict3["Date"] = "21/03/2014"; 
      dict3["Name"] = "aaa"; 
      list.Add(dict3); 

      Dictionary<string, string> dict4 = new Dictionary<string, string>(); 
      dict4["Date"] = "01/01/2015"; 
      dict4["Name"] = "ddd"; 
      list.Add(dict4); 

var ordered = list.OrderBy(x => x["Date"]); 
+0

每個字典只包含一個項目? – Alex 2015-03-02 12:35:22

+5

定義「不適當的結果」。另外,你的日期是一個字符串,它會像一個字符串一樣排列。 – Jamiec 2015-03-02 12:35:34

+1

爲什麼當你可以使用一個元組來獲得相同的結果時,你使用了一個字典? – 2015-03-02 12:35:45

回答

4

在每個字典的Date條目是一個字符串,一個List一無所知如何根據日期排序規則字符串進行排序。

一(可怕的)選擇是每根弦在點轉換爲相應的日期排序它

var ordered = list.OrderBy(x => DateTime.ParseExact(x["Date"], "dd/MM/yyyy", CultureInfo.CurrentCulture)); 

我說糟糕的選擇,因爲有字典的名單似乎有點像可濫用的格局,您應該可能擁有屬性爲NameDate的對象列表,其中Date屬性實際上是DateTime類型。

+0

你應該爲'ParseExact'提供'IFormatProvider'來工作。 – user3021830 2015-03-02 12:40:20

+0

@ user3021830 - 是的,謝謝你的光臨 – Jamiec 2015-03-02 12:41:11

+0

如果現在的文化不好,還是不行。這將得到一個'FormatException'說。 *字符串未被識別爲有效的日期時間。*此時文化被設置爲tr-TR時發生在我身上。我可以建議使用'IFormatProvider'作爲參數嗎? – user3021830 2015-03-02 12:43:44