4.8 Reverse the contents of the sorted list
Problem
You want to invert the contents of the sorted list in both the array and list types while maintaining the original functionality of the SortedList and sortedlist<t> classes. Both the SortedList and generic sortedlist<t> classes provide a straightforward way to complete this function without having to refill the list.
Solution
Reversiblesortedlist<tkey, the Tvalue> class provides these features, which are based on the Sortedlist<tkey, Tvalue> class, so they have the same functionality, It provides additional functionality that is easy to reverse the sorted list.
After instantiating Reversiblesortedlist<tkey, tvalue>, the key is an integer type, the value is a string type, a series of unordered numbers and their text expression are inserted into the list. These items are shown in this way:
ReversibleSortedList<int, string> rsl = new ReversibleSortedList<int, string>();
rsl.Add(2, "2");
rsl.Add(5, "5");
rsl.Add(3, "3");
rsl.Add(1, "1");
foreach (KeyValuePair<int, string> kvp in rsl)
{
Debug.WriteLine("\t" + kvp.Key + "\t" + kvp.Value);
}
The list output appears sorted in ascending order (default):
1 1
2 2
3 3 5 5
The order is now reversed by setting the Reversiblesortedlist SortDirection property to descending order. The sort () method needs to be called in order to reorder. The results are as follows:
// 转换排序方向.
rsl.Comparer.SortDirection = ListSortDirection.Descending;
// 重排列表.
rsl.Sort();
foreach (KeyValuePair<int, string> kvp in rsl)
{
Debug.WriteLine("\t" + kvp.Key + "\t" + kvp.Value);
}
This time, the output is in descending order:
5 5
3 3
2 2 1 1
When you add a new item to the list, it will be added in the current order, but you can keep the order of the elements in the list by reversing it immediately after adding all the items.
Rsl. ADD (4, "4");
foreach (Keyvaluepair<int, string> kvp in RSL)
{
Debug.WriteLine ("\ t" + kvp.) Key + "\ T" + kvp. Value);
}
Converts the sort direction.
Rsl.Comparer.SortDirection = listsortdirection.ascending;
Rearrange the tables.
Rsl. Sort ();
foreach (Keyvaluepair<int, string> kvp in RSL)
{
Debug.WriteLine ("\ t" + kvp.) Key + "\ T" + kvp. Value);
}
You can see that the new item is in descending order as well as ascending:
5 5
4 4
3 3 2 2 1 1 1 1 2 2-3 3
4 4
5 5