当前位置:   article > 正文

C#字典排序(按Key值、Value值顺序【升序】逆序【降序】排序)_c# 字典排序

c# 字典排序

字典的排序,简单做个笔记,方便查询(引用命名空间using System.Linq;):

  1. Dictionary<int, int> tempDict = new Dictionary<int, int>();
  2. var sortResult1 = from pair in tempDict orderby pair.Value descending select pair; //以字典Value值逆序排序[降序]
  3. var sortResult2 = from pair in tempDict orderby pair.Key descending select pair; //以字典Key值逆序排序[降序]
  4. var sortResult3 = from pair in tempDict orderby pair.Key ascending select pair; //以字典Key值顺序排序[升序]
  5. var sortResult4 = from pair in tempDict orderby pair.Value ascending select pair; //以字典Value值顺序排序[升序]

总结:

  1. 需要注意的是,得到的排序结构sortResult1,2,3,4是一个迭代器 IOrderedEnumerable<> 了,不再是字典,如果这样写则是错误的:
Dictionary<int, int> sortResult1 = from pair in tempDict orderby pair.Value descending select pair; //以字典Value值逆序排序
  1. 如果字典的key值或Value值是引用类型的,可以根据根据引用类型中的某个字段来排序:
  1. public class Info
  2. {
  3. public int m_ID;
  4. }
  5. Dictionary<int, Info> tempDict = new Dictionary<int, Info>();
  6. var sortResult1 = from pair in tempDict orderby pair.Value.m_ID descending select pair; //以字典Value值的字段 m_ID 逆序排序

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_42205218/article/details/105934030
 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/84496
推荐阅读
相关标签
  

闽ICP备14008679号