首页 > 技术文章 > C# 键值对排序

aiqingqing 2015-06-29 19:02 原文

static void Main(string[] args)
      {
         SortedList sl = new SortedList();

         sl.Add("001", "Zara Ali");
         sl.Add("002", "Abida Rehman");
         sl.Add("003", "Joe Holzner");
         sl.Add("004", "Mausam Benazir Nur");
         sl.Add("005", "M. Amlan");
         sl.Add("006", "M. Arif");
         sl.Add("007", "Ritesh Saikia");

         if (sl.ContainsValue("Nuha Ali"))
         {
            Console.WriteLine("This student name is already in the list");
         }
         else
         {
            sl.Add("008", "Nuha Ali");
         }

         // 获取键的集合 
         ICollection key = sl.Keys;

         foreach (string k in key)
         {
            Console.WriteLine(k + ": " + sl[k]);
         }
      }
=======================================================================

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

C# .net 3.5 以上的版本引入 Linq 后,字典Dictionary排序变得十分简单,用一句类似 sql 数据库查询语句即可搞定;不过,.net 2.0 排序要稍微麻烦一点,为便于使用,将总结 .net 3.5 和 2.0 的排序方法。

 

  一、创建字典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); 即可。

 

推荐阅读