سؤال

I have an unsorted Dictionary<int, Dictionary<int, string>> and when trying to sort its value's Keys its throwing System.ArgumentException: At least one object must implement IComparable. Following is the function,

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;
}

I am attaching the data screen shot below where you can see the keys unsorted so you have an idea what i am trying to achieve, surly i am doing something wrong and i need your guidance, thanks

enter image description here

هل كانت مفيدة؟

المحلول

Dictionary is, by design, inherently unsorted. If you sort the dictionary values, then convert it back to a Dictionary, you'll end up with an unsorted collection again.

That being said, the error is occuring because you're trying to call OrderBy with a KeyCollection, which isn't a sortable type.

You may want to consider some other collection, such as a SortedDictionary<T,U>. This will require writing a custom comparer to maintain the sort, however.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top