【问题标题】:C# - Dictionary<int, Dictionary<int, string>> sorting is throwing System.ArgumentExceptionC# - Dictionary<int, Dictionary<int, string>> 排序抛出 System.ArgumentException
【发布时间】:2012-10-04 16:58:06
【问题描述】:

我有一个未排序的Dictionary&lt;int, Dictionary&lt;int, string&gt;&gt;,当尝试对其值的键进行排序时,它的抛出System.ArgumentException: At least one object must implement IComparable. 以下是函数,

private static Dictionary<int, Dictionary<int, string>> SortDictionary(Dictionary<int, Dictionary<int, string>> unSortedDict)
{
      var sortedDict = (unSortedDict.OrderBy(entry => entry.Value.Keys)).ToDictionary(pair => pair.Key, pair => pair.Value);

      return sortedDict;
}

我附上了下面的数据屏幕截图,您可以在其中看到未排序的键,以便您了解我想要实现的目标,我做错了什么,我需要您的指导,谢谢

【问题讨论】:

  • 我需要更好的眼镜才能阅读屏幕截图中的文字...

标签: c# sorting dictionary icomparable argumentexception


【解决方案1】:

根据设计,字典本质上是未排序的。如果您对字典值进行排序,然后将其转换回字典,您将再次得到一个未排序的集合。

话虽如此,发生错误是因为您尝试使用KeyCollection 调用OrderBy,这不是可排序的类型。

您可能需要考虑其他一些集合,例如SortedDictionary&lt;T,U&gt;。然而,这将需要编写一个自定义比较器来维护排序。

【讨论】:

  • 有一个SortedDictionary 可能适合您的需求。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-04
  • 1970-01-01
  • 1970-01-01
  • 2018-01-25
  • 2021-10-20
  • 2011-03-05
相关资源
最近更新 更多