简体   繁体   中英

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

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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