Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order a dictionary without using Linq OrderBy

I'm trying to order a C# Dictionary<int, int> by its value without using LINQ's OrderBy as it's not supported on iPhones.

I can't seem to figure it out, so your help would be much appreciated!

like image 751
Fluup Avatar asked Dec 09 '25 03:12

Fluup


1 Answers

There are many possible ways of doing this. All of the following assume myDictionary is the original dictionary to be sorted.

① Create a list and then sort the list

var myList = myDictionary.ToList();
myList.Sort((a, b) => a.Value.CompareTo(b.Value));

② Create an array and then sort the array

var myArray = myDictionary.ToArray();
Array.Sort(myArray, (a, b) => a.Value.CompareTo(b.Value));

③ Create a new SortedDictionary that has keys and values swapped

This solution is appropriate only if you know that every value occurs only once.

var mySortedDict = new SortedDictionary<int, int>();
foreach (var kvp in myDictionary)
    mySortedDict[kvp.Value] = kvp.Key;

④ Create a new SortedDictionary and use lists for values

This solution is appropriate only if values can occur more than once.

var mySortedDict = new SortedDictionary<int, List<int>>();
foreach (var kvp in myDictionary)
{
    if (!mySortedDict.ContainsKey(kvp.Value))
        mySortedDict[kvp.Value] = new List<int>();
    mySortedDict[kvp.Value].Add(kvp.Key);
}
like image 141
Timwi Avatar answered Dec 10 '25 17:12

Timwi