- /*使用排序字典,默认只支持升序
- 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");
- //可以借助List得到降序键或值
- List<String> lst = new List<String>(dd.Values);
- lst.Reverse();
- */
- /*使用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);
- }
- //或
- Dictionary<DateTime, String> dd2 = result.ToDictionary(p=>p.Key, p=>p.Value);
- */
- //使用扩展方法
- 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);
![](https://img2024.cnblogs.com/blog/35695/202408/35695-20240826070647288-243310440.jpg)