一、創建字典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 />"); }