C#字典Dictionary排序(顺序、倒序、先 Value 再按 Key 排、按键长短排)
C# .net 3.5 以上的版本引入 Linq 后,字典Dictionary排序变得十分简单,用一句类似 sql 数据库查询语句即可搞定;不过,.net 2.0 排序要稍微麻烦一点,为便于使用,将总结 .net 3.5 和 2.0 的排序方法。
在 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 3.5 以上版本 Dictionary排序(即 linq dictionary 排序)
1、Dictionary按值value排序
private void DictionarySort(Dictionary<string, int> dic)
{
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 />");
}
排序结果(倒序):
index.html:50
online.aspx:22
news.aspx:18
product.html:13
aboutus.html:4
上述代码是按降序(倒序)排列,如果想按升序(顺序)排列,只需要把变量 dicSort 右边的 descending 去掉即可。
2、C# Dictionary key 排序
如果要按 Key 排序,只需要把变量 dicSort 右边的 objDic.Value 改为 objDic.Key 即可。
3、C# Dictionary 先按值 Value 再按键 Key 排序
假如要先按值 Value 升序排序再按键 Key 降序排序,代码如下:
private IOrderedEnumerable<KeyValuePair<string, int>> DictionarySort(Dictionary<string, int> dic)
{
return dic.OrderBy(i => i.Value).OrderByDescending(i => i.Key);
}
调用:
var dicSort = DictionarySort(dic);
排序结果:
product.html:13
online.aspx:22
news.aspx:18
index.html:50
aboutus.html:4
4、C# Dictionary 按键 Key 的长度排序
假如要求根据键 Key 的长度排序,短的排在先、长的排在后,代码如下:
private IOrderedEnumerable<KeyValuePair<string, int>> DictionarySort(Dictionary<string, int> dic)
{
return dic.OrderBy(i => i.Key.Length);
}
调用:
var dicSort = DictionarySort(dic);
排序结果:
news.aspx:18
index.html:50
online.aspx:22
product.html:13
aboutus.html:4
假如要求长的排在先、短的排在后,只需把代码改为:
return dic.OrderByDescending(i => i.Key.Length);
三、.net 2.0 版本 Dictionary排序
1、dictionary按值value排序(倒序)
private void DictionarySort(Dictionary<string, int> dic)
{
if (dic.Count > 0)
{
List<KeyValuePair<string, int>> lst = new List<KeyValuePair<string, int>>(dic);
lst.Sort(delegate(KeyValuePair<string, int> s1, KeyValuePair<string, int> s2)
{
return s2.Value.CompareTo(s1.Value);
});
dic.Clear();
foreach (KeyValuePair<string, int> kvp in lst)
Response.Write(kvp.Key + ":" + kvp.Value + "<br />");
}
}
排序结果:
index.html:50
online.aspx:22
news.aspx:18
product.html:13
aboutus.html:4
顺序排列:只需要把变量 return s2.Value.CompareTo(s1.Value); 改为 return s1.Value.CompareTo(s2.Value); 即可。
2、C# dictionary key 排序(倒序、顺序)
如果要按 Key 排序,倒序只需把 return s2.Value.CompareTo(s1.Value); 改为 return s2.Key.CompareTo(s1.Key);;顺序只需把return s2.Key.CompareTo(s1.Key); 改为 return s1.Key.CompareTo(s2.Key); 即可。