5.8. Sorting a Dictionary's Keys and/or Values
Problem
You want to sort the keys and/or values contained in a Dictionary in order to display the entire Dictionary to the user, sorted in either ascending or descending order.
Solution
Use a LINQ query and the Keys and Values properties of a Dictionary<T,U> object to obtain a sorted ICollection of its key and value objects. The code shown here displays the keys and values of a Dictionary<T,U> sorted in ascending or descending order:
var x = from k in hash.Keys orderby k ascending select k;
foreach (string s in x)
Console.WriteLine("Key: " + s + " Value: " + hash[s]);
x = from k in hash.Keys orderby k descending select k;
foreach (string s in x)
Console.WriteLine("Key: " + s + " Value: " + hash[s]);The code shown here displays the values in a Dictionary<T,U> sorted in ascending or descending order:
var x = from k in hash.Values orderby k ascending select k;
foreach (string s in x)
Console.WriteLine("Value: " + s);
Console.WriteLine( );
x = from k in hash.Values orderby k descending select k;
foreach (string s in x)
Console.WriteLine("Value: " + s);Note that you can also use the SortedDictionary<T,U> class, which will automatically keep the key sorted for you.
Discussion
The Dictionary<T,U> object exposes two useful properties for obtaining a collection of its keys or values. The Keys property returns an ICollection containing all the keys currently in the Dictionary<T,U>. The Values property returns the same for all values currently contained ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access