Anyone who has used a dictionary knows that sorteddictionary is used when sorting values in each add without changing the order. However, sorteddictionary is not ideal, the default method only supports Positive Sorting. To reverse sorting, you must rewrite the code by yourself. Here is a simple example:
The test environment is Web. For example, in winform, you only need to modify the output statement for debugging.
If the following code cannot be used during debugging, it must be referenced:
Using system. LINQ;
Using system. Collections. Generic;
1 private void testdictionarysort ()
2 {
3 sorteddictionary <string, string> SD = new sorteddictionary <string, string> ();
4 SD. Add ("321", "fdsgsags ");
5 SD. Add ("ACB", "test ");
6 SD. Add ("1123", "lslgsgl ");
7 SD. Add ("2bcd13", "value ");
8 SD. Reverse (); // the built-in reverse order is invalid.
9
10 foreach (keyvaluepair <string, string> item in SD)
11 {
12 response. Write ("key name:" + item. Key + "key value:" + item. value );
13}
14
15}
Output result of the above Code:
Key: 1123 key value: lslgsgl
Key name: 2bcd13 key value: Value
Key: 321 key value: fdsgsags
Key name: ACB key value: Test test
The result proves that "SD. reverse (); "is invalid. Well, now we want to use an alternative method to make it take effect to achieve reverse sorting. Please refer to the following code:
Private void testdictionarysort ()
{
Sorteddictionary <string, string> SD = new sorteddictionary <string, string> ();
SD. Add ("321", "fdsgsags ");
SD. Add ("ACB", "test ");
SD. Add ("1123", "lslgsgl ");
SD. Add ("2bcd13", "value ");
Response. Write ("<br/> sort data in positive order: <br/> ");
Foreach (keyvaluepair <string, string> item in SD)
{
Response. Write ("key name:" + item. Key + "key value:" + item. Value + "<br/> ");
}
// Re-encapsulate it into the dictionary (PS: we will not use the sort after sorting, so we will use the dictionary)
Dictionary <string, string> Dc = new dictionary <string, string> ();
Foreach (keyvaluepair <string, string> item in SD. Reverse ())
{
DC. Add (item. Key, item. value );
}
SD = NULL;
// View the output result again:
Response. Write ("<br/> reverse sort data: <br/> ");
Foreach (keyvaluepair <string, string> item in DC)
{
Response. Write ("key name:" + item. Key + "key value:" + item. Value + "<br/> ");
}
}
Output result of the above Code:
Sort data in positive order:
Key: 1123 key value: lslgsgl
Key name: 2bcd13 key value: Value
Key: 321 key value: fdsgsags
Key name: ACB key value: Test test
Sort data in reverse order:
Key name: ACB key value: Test test
Key: 321 key value: fdsgsags
Key name: 2bcd13 key value: Value
Key: 1123 key value: lslgsgl