4.7. Reversing the Contents of a Sorted List
Problem
You want to be able to reverse the contents of a sorted list of items while also maintaining the ability to access them in both array and list styles like SortedList and the generic SortedList<T> classes provide. Neither SortedList nor SortedList<T> provides a direct way to accomplish this without reloading the list.
Solution
Use LINQ to Objects to query the SortedList<T> and apply a descending order to the information in the list. After instantiating a SortedList<TKey, TValue>, the key of which is an int and the value of which is a string, a series of unordered numbers and their text representations are inserted into the list. Those items are then displayed:
SortedList<int, string> data = new SortedList<int, string>();
data.Add(2, "two");
data.Add(5, "five");
data.Add(3, "three");
data.Add(1, "one");
foreach (KeyValuePair<int, string> kvp in data)
{
Debug.WriteLine("\t" + kvp.Key + "\t" + kvp.Value);
}The output for the list is shown sorted in ascending order (the default):
1 one 2 two 3 three 5 five
Now the sort order is reversed by creating a query using LINQ to Objects and setting the orderby clause to descending. The results are then displayed from the query result set:
// query ordering by descending
var query = from d in data
orderby d.Key descending
select d;
foreach (KeyValuePair<int, string> kvp in query)
{
Debug.WriteLine("\t" + kvp.Key + "\t" + kvp.Value);
}This time the output is in descending order:
5 five 3 three 2 ...
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