我有一个字典列表,我希望它按日期键降序排序。但是下面的查询给出了不合适的结果。请帮忙。
日期格式为 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"]);
请您参考如下方法:
每个字典中的 Date 条目都是一个字符串,List 对如何根据日期排序规则对字符串进行排序一无所知。
一个(糟糕的)选择是在订购时将每个字符串转换为适当的日期
var ordered = list.OrderBy(x => DateTime.ParseExact( x["Date"], "dd/MM/yyyy", CultureInfo.CurrentCulture));
我说的是糟糕的选择,因为拥有字典列表似乎是一种可滥用的模式,您可能应该拥有具有属性 Name 和 Date 的对象列表其中 Date 属性实际上是 DateTime 类型。
