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 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 + “
”);
  }

排序结果:

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 + “
”);
    }
  }

排序结果:

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); 即可。

猜你喜欢

转载自blog.csdn.net/quailchivalrous/article/details/104185775