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

1、建立字典Dictionary 對象

  假如 Dictionary 中保存的是一個網站頁面流量,key 是網頁名稱,值value對應的是網頁被訪問的次數,因爲網頁的訪問次要不斷的統計,因此不能用 int 做爲 key,只能用網頁名稱,建立 Dictionary 對象及添加數據代碼以下:html

複製代碼
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);
複製代碼

2、.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); });spa

複製代碼

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

  使用linq排序.net

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 />");
}
相關文章
相關標籤/搜索