假如 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);
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
使用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 />"); }