您的位置:首页 > 其它

dictonary按键值进行排序

2016-12-06 17:00 302 查看
用排序字典,默认只支持升序 

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);  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: