繁体   English   中英

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

[英]Sorting a list of dictionary based on a key in 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"]);

每个词典中的“ Date条目都是一个字符串,“ List对于如何根据日期排序规则对字符串进行排序一无所知。

一个(糟糕的)选择是在订购时将每个字符串转换为适当的日期

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

我说这是一个糟糕的选择,因为拥有字典列表似乎有点可滥用的模式,您可能应该拥有具有属性NameDate的对象列表,其中Date属性实际上是DateTime类型。

暂无
暂无

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

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