C#字典Dictionary排序(顺序、倒序)
·
这里是针对.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;
Dictionary<int, int> tempDict = new Dictionary<int, int>();
var sortResult1 = from pair in tempDict orderby pair.Value descending select pair; //以字典Value值逆序排序
var sortResult2 = from pair in tempDict orderby pair.Key descending select pair; //以字典Key值逆序排序
var sortResult3 = from pair in tempDict orderby pair.Key ascending select pair; //以字典Key值顺序排序
var sortResult4 = from pair in tempDict orderby pair.Value ascending select pair; //以字典Value值顺序排序
- 需要注意的是,得到的排序结构sortResult1,2,3,4是一个迭代器 IOrderedEnumerable<> 了,不再是字典,如果这样写则是错误的
Dictionary<int, int> sortResult1 = from pair in tempDict orderby pair.Value descending select pair; //以字典Value值逆序排序
-
如果字典的key值或Value值是引用类型的,可以根据根据引用类型中的某个字段来排序:
public class Info
{
public int m_ID;
}
Dictionary<int, Info> tempDict = new Dictionary<int, Info>();
var sortResult1 = from pair in tempDict orderby pair.Value.m_ID descending select pair; //以字典Value值的字段 m_ID 逆序排序
输出要用这个输出:
foreach(KeyValuePair<string, int> kvp in dicSort)
{
Response.Write(kvp.Key + ":" + kvp.Value + "<br />");
}
法三:
Dictionary<string, string> dic1 = new Dictionary<string, string>(); dic1.Add("ddd","123");
dic1.Add("aaa", "123");
dic1.Add("ccc", "123");
dic1.Add("fff", "123");
dic1.Add("eee", "123");
dic1.Add("bbb", "123");
Dictionary<string, string> dic1Asc = dic1.OrderBy(o => o.Key).ToDictionary(o => o.Key, p => p.Value);
Dictionary<string, string> dic1desc = dic1.OrderByDescending(o => o.Key).ToDictionary(o => o.Key, p => p.Value);
Dictionary<string, string> dic1Asc1 = (from d in dic1 orderby d.Key ascending select d).ToDictionary(k => k.Key, v => v.Value);
Dictionary<string, string> dic1desc2 = (from d in dic1 orderby d.Key descending select d).ToDictionary(k => k.Key, v => v.Value);
List<string> list = new List<string>();
list.Add("aaa");
list.Add("ddd");
list.Add("bbb");
list.Add("ccc");
list.Add("bbb");
var ascList = list.OrderBy(o => o);
var descList = list.OrderByDescending(o => o);
var ascList1 = (from l in list orderby l ascending select l).ToList();
var descList2 = (from l in list orderby l descending select l).ToList();
string str = "";
更多推荐
已为社区贡献17条内容
所有评论(0)