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 />");
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM