【问题标题】:Sorting a list of dictionary based on a key in C#基于C#中的键对字典列表进行排序
【发布时间】:2015-05-02 19:28:33
【问题描述】:

我有一个字典列表,我希望它按日期键降序排序。但是以下查询给出了不适当的结果。请帮忙。

日期格式为 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 参数的类型是 String 而不是 DateTime。你怎么能期望它正确排序?
  • 您不需要更改 SP。您仍然可以将其存储在 字典中,然后正确排序。

标签: c# linq sorting dictionary


【解决方案1】:

每个字典中的Date 条目是一个字符串,List 不知道如何根据日期排序规则对字符串进行排序。

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

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

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

【讨论】:

  • 您应该提供IFormatProvider 以便ParseExact 工作。
  • 如果当前的文化不正常,仍然无法工作。这将得到FormatException 的说法。 字符串未被识别为有效的 DateTime。 目前文化设置为 tr-TR 时发生在我身上。我可以建议使用IFormatProvider 作为参数吗?
  • 谢谢...它对我来说工作正常。我试过了,但我使用的是 Convert.ToDateTime 而不是 DateTime.ParseExact,它给了我错误。
猜你喜欢
  • 1970-01-01
  • 2013-07-21
  • 2014-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-30
  • 2015-11-23
相关资源
最近更新 更多