温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

c# 字典排序

发布时间:2020-05-15 10:16:31 来源:亿速云 阅读:193 作者:Leah 栏目:编程语言

这篇文章主要介绍了c# 字典dictionary的排序方法,具有一定借鉴价值,需要的朋友可以参考下。如下资料是关于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 3.5 以上版本 Dictionary排序(即 linq dictionary 排序)

  1、dictionary按值value排序

 private void DictonarySort(Dictionary<string, int> dic)
  {
    var dicSort = from objDic in dic orderby objDic.Value descending select objDic;
    foreach(KeyValuePair<string, int> kvp in dicSort)
      Response.Write(kvp.Key + ":" + kvp.Value + "<br />");
  }

 排序结果:

  index.html:50
  online.aspx:22
  news.aspx:18
  product.html:13
  aboutus.html:4

  上述代码是按降序(倒序)排列,如果想按升序(顺序)排列,只需要把变量 dicSort 右边的 descending 去掉即可。

  2、C# dictionary key 排序

  如果要按 Key 排序,只需要把变量 dicSort 右边的 objDic.Value 改为 objDic.Key 即可。

三、.net 2.0 版本 Dictionary排序

  1、dictionary按值value排序(倒序)

private void DictionarySort(Dictionary<string, int> dic)
  {
    if (dic.Count > 0)
    {
      List<KeyValuePair<string, int>> lst = new List<KeyValuePair<string, int>>(dic);
      lst.Sort(delegate(KeyValuePair<string, int> s1, KeyValuePair<string, int> s2)
      {
        return s2.Value.CompareTo(s1.Value);
      });
      dic.Clear();

      foreach (KeyValuePair<string, int> kvp in lst)
        Response.Write(kvp.Key + ":" + kvp.Value + "<br />");
    }
  }

排序结果:

  index.html:50
  online.aspx:22
  news.aspx:18
  product.html:13
  aboutus.html:4

  顺序排列:只需要把变量 return s2.Value.CompareTo(s1.Value); 改为 return s1.Value.CompareTo(s2.Value); 即可。

2、C# dictionary key 排序(倒序、顺序)

  如果要按 Key 排序,倒序只需把 return s2.Value.CompareTo(s1.Value); 改为 return s2.Key.CompareTo(s1.Key);;顺序只需把return s2.Key.CompareTo(s1.Key); 改为 return s1.Key.CompareTo(s2.Key); 即可。

以上就是dictionary的详细内容,代码示例简单明了,如果在日常工作遇到此问题。通过这篇文章,希望你能有所收获,更多详情敬请关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI