Skip to main content
 首页 » 编程设计

C#之Dictionaryint, Dictionaryint, string>> 排序抛出 System.ArgumentException

2024年02月20日18wayfarer

我有一个未排序的 Dictionary<int, Dictionary<int, string>>并在尝试对其值的键进行排序时抛出 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; 
} 

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

请您参考如下方法:

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

也就是说,发生错误是因为您正在尝试调用 OrderBy用 KeyCollection ,这不是可排序的类型。

您可能需要考虑一些其他集合,例如 SortedDictionary<T,U> .但是,这将需要编写自定义比较器来维护排序。