这里是针对.NET版本过低的排序方式,没怎么用过,记录一下;
一、创建字典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);
});
dic.Clear();
三、.net 3.5 以上版本 Dictionary排序(即 linq dictionary 排序)
使用linq排序
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 />");
}
