C# 键值对数据排序

  1. /*使用排序字典,默认只支持升序 
  2. SortedDictionary<DateTime, String> dd = new SortedDictionary<DateTime, String>(); 
  3. DateTime dt = DateTime.Now; 
  4. dd.Add(dt, "bbb"); 
  5. dd.Add(dt.AddDays(-1), "ccc"); 
  6. dd.Add(dt.AddDays(1), "aaa"); 
  7. //可以借助List得到降序键或值 
  8. List<String> lst = new List<String>(dd.Values); 
  9. lst.Reverse(); 
  10. */  
  11.   
  12. /*使用Linq查询 
  13. Dictionary<DateTime, String> dd = new Dictionary<DateTime, String>(); 
  14. DateTime dt = DateTime.Now; 
  15. dd.Add(dt, "bbb"); 
  16. dd.Add(dt.AddDays(-1), "ccc"); 
  17. dd.Add(dt.AddDays(1), "aaa"); 
  18.  
  19. var result = from pair in dd orderby pair.Key descending select pair; 
  20. List<String> lst = new List<String>(); 
  21. foreach (var kv in result) 
  22. { 
  23.     lst.Add(kv.Value); 
  24. } 
  25. //或 
  26. Dictionary<DateTime, String> dd2 = result.ToDictionary(p=>p.Key, p=>p.Value); 
  27. */  
  28.   
  29. //使用扩展方法  
  30. Dictionary<DateTime, String> dd = new Dictionary<DateTime, String>();  
  31. DateTime dt = DateTime.Now;  
  32. dd.Add(dt, "bbb");  
  33. dd.Add(dt.AddDays(-1), "ccc");  
  34. dd.Add(dt.AddDays(1), "aaa");  
  35.   
  36. Dictionary<DateTime, String> dicAsc = dd.OrderBy(p=>p.Key).ToDictionary(p=>p.Key, p=>p.Value);  
  37. Dictionary<DateTime, String> dicDesc = dd.OrderByDescending(p=>p.Key).ToDictionary(p=>p.Key, p=>p.Value); 

猜你喜欢

转载自blog.csdn.net/yelin042/article/details/80780061