C# 根据C中的键对字典列表进行排序#
我有一个字典列表,我希望它按日期键降序排序。但是下面的查询给出了不适当的结果。请帮忙 日期格式为DD/MM/YYYYC# 根据C中的键对字典列表进行排序#,c#,linq,sorting,dictionary,C#,Linq,Sorting,Dictionary,我有一个字典列表,我希望它按日期键降序排序。但是下面的查询给出了不适当的结果。请帮忙 日期格式为DD/MM/YYYY List<Dictionary<string, string>> list = new List<Dictionary<string, string>>(); Dictionary<string, string> dict1 = new Dictionary<string, string&g
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"]);
List List=新列表();
Dictionary dict1=新字典();
第1条[“日期”]=“2015年3月1日”;
dict1[“Name”]=“bbb”;
增加(1);
Dictionary dict2=新字典();
第2条[“日期”]=“2014年8月11日”;
dict2[“名称”]=“ccc”;
增加(2);
Dictionary dict3=新字典();
第3条[“日期”]=“2014年3月21日”;
dict3[“Name”]=“aaa”;
增加(3);
Dictionary dict4=新字典();
第4条[“日期”]=“2015年1月1日”;
dict4[“Name”]=“ddd”;
增加(第4条);
var ordered=list.OrderBy(x=>x[“日期”]);
每个词典中的日期
条目都是一个字符串,列表
不知道如何根据日期排序规则对字符串进行排序
一个(糟糕的)选择是在排序时将每个字符串转换为适当的日期
var ordered = list.OrderBy(x => DateTime.ParseExact( x["Date"], "dd/MM/yyyy", CultureInfo.CurrentCulture));
我说这是一个糟糕的选择,因为拥有一个字典列表似乎有点像一个可滥用的模式,您可能应该有一个具有属性
Name
和Date
的对象列表,其中Date
属性的类型实际上是DateTime每个字典中的Date
条目是一个字符串,列表
不知道如何根据日期排序规则对字符串进行排序
一个(糟糕的)选择是在排序时将每个字符串转换为适当的日期
var ordered = list.OrderBy(x => DateTime.ParseExact( x["Date"], "dd/MM/yyyy", CultureInfo.CurrentCulture));
我说这是一个糟糕的选择,因为拥有一个字典列表似乎有点像一个可利用的模式,您可能应该拥有一个具有属性Name
和Date
的对象列表,其中Date
属性实际上是类型DateTime每个字典只包含一个项?定义“不适当的结果“。此外,您的日期是一个字符串,它的顺序将与字符串一样。当您可以使用元组获得相同的结果时,您为什么要使用字典?您的date
参数是string类型,而不是DateTime
。你怎么能期望它正确排序?你不需要更改SP。你仍然可以将它存储在一个字典中,然后正确排序。每个字典只包含一个项目?定义“不适当的结果”。此外,您的日期是一个字符串,它的顺序与字符串的顺序相同。当可以使用元组获得相同的结果时,您为什么要使用字典?您的date
参数是string类型,而不是DateTime
。您怎么能期望它正确排序?您不需要更改SP。您仍然可以将其存储在字典中,然后正确排序。您应该提供IFormatProvider
,以便ParseExact
正常工作。如果当前区域性不正常,则仍然无法正常工作。这将得到一个FormatException
语句。字符串未被识别为有效的日期时间。这发生在我身上,而此时文化被设定为tr。我可以建议使用IFormatProvider
作为参数吗?谢谢……它对我来说很好。我尝试了它,但我使用了Convert.ToDateTime而不是DateTime.ParseExact,它给了我一个错误。你应该为ParseExact
提供IFormatProvider才能工作。如果当前区域性不正常,仍然无法工作。这将得到一个FormatException
语句。字符串未被识别为有效的日期时间。这发生在我身上,而此时文化被设定为tr。我可以建议使用IFormatProvider
作为参数吗?谢谢……它对我来说很好。我试过了,但我使用了Convert.ToDateTime而不是DateTime.ParseExact,它给了我一个错误。