2015-03-02 63 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