C#字典Dictionary排序(顺序、倒序) 您所在的位置:网站首页 vba字典排序与数组排序的区别在哪 C#字典Dictionary排序(顺序、倒序)

C#字典Dictionary排序(顺序、倒序)

2023-09-11 18:11| 来源: 网络整理| 查看: 265

 

这里是针对.NET版本过低的排序方式,没怎么用过,记录一下;

创建字典Dictionary 对象

  假如 Dictionary 中保存的是一个网站页面流量,key 是网页名称,值value对应的是网页被访问的次数,由于网页的访问次要不断的统计,所以不能用 int 作为 key,只能用网页名称,创建 Dictionary 对象及添加数据代码如下:

 

 

Dictionary dic = new Dictionary();   dic.Add("index.html", 50);   dic.Add("product.html", 13);   dic.Add("aboutus.html", 4);   dic.Add("online.aspx", 22);   dic.Add("news.aspx", 18); 法一、.net 2.0 版本 Dictionary排序

 

 

List lst = new List(dic);   //倒叙排列:只需要把变量s2 和 s1 互换就行了 例: return s1.Value.CompareTo(s2.Value);   //进行排序 目前是顺序       lst.Sort(delegate(KeyValuePair s1, KeyValuePair s2)       {         return s2.Value.CompareTo(s1.Value);       });       dic.Clear();

 

 

 

法二、.net 3.5 以上版本 Dictionary排序(即 linq dictionary 排序)

  使用linq排序

var dicSort = from objDic in dic orderby objDic.Value descending select objDic; Dictionary tempDict = new Dictionary(); var sortResult1 = from pair in tempDict orderby pair.Value descending select pair; //以字典Value值逆序排序 var sortResult2 = from pair in tempDict orderby pair.Key descending select pair; //以字典Key值逆序排序 var sortResult3 = from pair in tempDict orderby pair.Key ascending select pair; //以字典Key值顺序排序 var sortResult4 = from pair in tempDict orderby pair.Value ascending select pair; //以字典Value值顺序排序  需要注意的是,得到的排序结构sortResult1,2,3,4是一个迭代器 IOrderedEnumerable 了,不再是字典,如果这样写则是错误的 Dictionary sortResult1 = from pair in tempDict orderby pair.Value descending select pair; //以字典Value值逆序排序

 

 

如果字典的key值或Value值是引用类型的,可以根据根据引用类型中的某个字段来排序:

 public class Info { public int m_ID; } Dictionary tempDict = new Dictionary(); var sortResult1 = from pair in tempDict orderby pair.Value.m_ID descending select pair; //以字典Value值的字段 m_ID 逆序排序  

 

  输出要用这个输出:

  

foreach(KeyValuePair kvp in dicSort) {   Response.Write(kvp.Key + ":" + kvp.Value + ""); } 法三: Dictionary dic1 = new Dictionary(); dic1.Add("ddd","123"); dic1.Add("aaa", "123"); dic1.Add("ccc", "123"); dic1.Add("fff", "123"); dic1.Add("eee", "123"); dic1.Add("bbb", "123"); Dictionary dic1Asc = dic1.OrderBy(o => o.Key).ToDictionary(o => o.Key, p => p.Value); Dictionary dic1desc = dic1.OrderByDescending(o => o.Key).ToDictionary(o => o.Key, p => p.Value); Dictionary dic1Asc1 = (from d in dic1 orderby d.Key ascending select d).ToDictionary(k => k.Key, v => v.Value); Dictionary dic1desc2 = (from d in dic1 orderby d.Key descending select d).ToDictionary(k => k.Key, v => v.Value); List list = new List(); list.Add("aaa"); list.Add("ddd"); list.Add("bbb"); list.Add("ccc"); list.Add("bbb"); var ascList = list.OrderBy(o => o); var descList = list.OrderByDescending(o => o); var ascList1 = (from l in list orderby l ascending select l).ToList(); var descList2 = (from l in list orderby l descending select l).ToList(); string str = "";

 



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有