Sort a Dictionary by value in c#
- Authors
- Name
- Brent
Sorting a dictionary by value in C# can be achieved by first creating a list of KeyValuePair objects from the dictionary, and then sorting the list using the LINQ
method OrderBy
or OrderByDescending
.
Here is an example of how to sort a dictionary in ascending order by value:
Dictionary<string, int> myDictionary = new Dictionary<string, int>()
{
{"apple", 3},
{"banana", 2},
{"cherry", 1},
{"date", 4}
};
List<KeyValuePair<string, int>> myList = myDictionary.ToList();
myList.Sort((firstPair,nextPair) => firstPair.Value.CompareTo(nextPair.Value));
foreach(KeyValuePair<string, int> kvp in myList)
{
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
Output:
Key = cherry, Value = 1
Key = banana, Value = 2
Key = apple, Value = 3
Key = date, Value = 4
To sort in descending order, you can use the OrderByDescending
method instead of OrderBy
myList = myDictionary.OrderByDescending(x => x.Value).ToList();
Output:
Key = date, Value = 4
Key = apple, Value = 3
Key = banana, Value = 2
Key = cherry, Value = 1
Note that, this method creates a new list and copies all elements from the dictionary, which can be inefficient for large dictionaries.
If you need to sort a large dictionary, you can use a SortedDictionary
instead of a regular Dictionary.