zoukankan      html  css  js  c++  java
  • C#字典Dictionary排序(顺序、倒序)

    一、创建字典Dictionary 对象

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

    复制代码
    Dictionary<string, int> dic = new Dictionary<string, int>();
      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<KeyValuePair<string, int>> lst = new List<KeyValuePair<string, int>>(dic);

      //倒叙排列:只需要把变量s2 和 s1 互换就行了 例: return s1.Value.CompareTo(s2.Value);
      //进行排序 目前是顺序

          lst.Sort(delegate(KeyValuePair<string, int> s1, KeyValuePair<string, int> s2)  
          {
            return s2.Value.CompareTo(s1.Value);
          });
          

    List<KeyValuePair<string,int>> list=new List<KeyValuePair<string, int>>(dic);
    list.Sort((s1, s2) => { return s1.Value.CompareTo(s2.Value); });

    复制代码

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

      使用linq排序

    var dicSort = from objDic in dic orderby objDic.Value descending select objDic;
    var dicNew = dic.OrderBy(s1=>s1.Value);
    输出要用这个输出:
    foreach(KeyValuePair<string, int> kvp in dicSort)
    {
      Response.Write(kvp.Key + ":" + kvp.Value + "<br />");
    }
  • 相关阅读:
    Queue——C#浅谈
    C#设计模式(7)——适配器模式
    test
    python 技巧
    在centos 配置python django环境 总结
    pyqt5 做的小程序,可以用来UI做个小demo
    python sqlalthemy 总结
    数据清理,预处理 pandas dataframe 操作技巧 总结
    对区块链看法
    hadoop spark 总结
  • 原文地址:https://www.cnblogs.com/lip-blog/p/9498804.html
Copyright © 2011-2022 走看看