C # Sort data by key-value pairs,
Summarize the sorting methods of key-value pairs.
[Csharp]View plaincopy
- /* Use the sort dictionary. By default, only the ascending order is supported.
- SortedDictionary <DateTime, String> dd = new SortedDictionary <DateTime, String> ();
- DateTime dt = DateTime. Now;
- Dd. Add (dt, "bbb ");
- Dd. Add (dt. AddDays (-1), "ccc ");
- Dd. Add (dt. AddDays (1), "aaa ");
- // You can use List to obtain the descending key or value.
- List <String> lst = new List <String> (dd. Values );
- Lst. Reverse ();
- */
- /* Query using Linq
- Dictionary <DateTime, String> dd = new Dictionary <DateTime, String> ();
- DateTime dt = DateTime. Now;
- Dd. Add (dt, "bbb ");
- Dd. Add (dt. AddDays (-1), "ccc ");
- Dd. Add (dt. AddDays (1), "aaa ");
-
- Var result = from pair in dd orderby pair. Key descending select pair;
- List <String> lst = new List <String> ();
- Foreach (var kv in result)
- {
- Lst. Add (kv. Value );
- }
- // Or
- Dictionary <DateTime, String> dd2 = result. ToDictionary (p => p. Key, p => p. Value );
- */
- // Use the Extension Method
- Dictionary <DateTime, String> dd = new Dictionary <DateTime, String> ();
- DateTime dt = DateTime. Now;
- Dd. Add (dt, "bbb ");
- Dd. Add (dt. AddDays (-1), "ccc ");
- Dd. Add (dt. AddDays (1), "aaa ");
- Dictionary <DateTime, String> dicAsc = dd. OrderBy (p => p. Key). ToDictionary (p => p. Key, p => p. Value );
- Dictionary <DateTime, String> dicDesc = dd. OrderByDescending (p => p. Key). ToDictionary (p => p. Key, p => p. Value );