对于键值对的数据进行排序方法总结。
/*使用排序字典,默认只支持升序
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);