简体   繁体   English

根据C#中的键对字典列表进行排序

[英]Sorting a list of dictionary based on a key in C#

I have a list of dictionary and I want it sort on the date key in descending order. 我有一个字典列表,我希望它按降序在日期键上排序。 But the following query gives inappropriate result. 但是以下查询给出了不合适的结果。 Please help. 请帮忙。

Date format is DD/MM/YYYY 日期格式为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"]);

The Date entry in each of your dictionaries is a string, a List knows nothing about how to sort strings based on date ordering rules. 每个词典中的“ Date条目都是一个字符串,“ List对于如何根据日期排序规则对字符串进行排序一无所知。

One (terrible) option is to convert each string to an appropriate date at the point of ordering it 一个(糟糕的)选择是在订购时将每个字符串转换为适当的日期

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

I say terrible option, because having a List of dictionaries seems like a bit of an abusable pattern, you should probably have a List of objects with properties Name and Date where the Date property is actually of type DateTime . 我说这是一个糟糕的选择,因为拥有字典列表似乎有点可滥用的模式,您可能应该拥有具有属性NameDate的对象列表,其中Date属性实际上是DateTime类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM