Dictionary排序,用到的函数就两个:
正序:Enumerable.OrderBy<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey>)
反序:Enumerable.OrderByDescending<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey>)
创建一个Dictionary对象.并添加内容
Dictionary<string, string> dir = new Dictionary<string, string>();
dir .Add("1001", "xiaoming");
dir .Add("1002", "小明");
dir .Add("10086", "yidong");
dir .Add("asd", "value");
调用行数,应用lamda表达式的方式(msdn的列子就是这样的)对其进行各种排序
Dictionary<string, string> sd1 = dir.OrderByDescending(a => a.Key).ToDictionary(a => a.Key, a => a.Value);
Dictionary<string, string> sd2 = dir.OrderBy(a => a.Key).ToDictionary(a => a.Key, a => a.Value);
Dictionary<string, string> sd3 = dir.OrderByDescending(a => a.Value).ToDictionary(a => a.Key, a => a.Value);
Dictionary<string, string> sd4 = dir.OrderBy(a => a.Value).ToDictionary(a => a.Key, a => a.Value);
Dictionary<string, string> sd5 = dir.OrderBy(a => a.Key.Length).ToDictionary(a => a.Key, a => a.Value);
Console.WriteLine("----------------------按键反排序---------------------------");
foreach (KeyValuePair<string, string> item in sd1)
{
Console.WriteLine("键名:" + item.Key + " 键值:" + item.Value);
}
Console.WriteLine("----------------------按键正排序---------------------------");
foreach (KeyValuePair<string, string> item in sd2)
{
Console.WriteLine("键名:" + item.Key + " 键值:" + item.Value);
}
Console.WriteLine("----------------------按值反排序---------------------------");
foreach (KeyValuePair<string, string> item in sd3)
{
Console.WriteLine("键名:" + item.Key + " 键值:" + item.Value);
}
Console.WriteLine("----------------------按值正排序---------------------------");
foreach (KeyValuePair<string, string> item in sd4)
{
Console.WriteLine("键名:" + item.Key + " 键值:" + item.Value);
}
Console.WriteLine("----------------------按键长度正排序---------------------------");
foreach (KeyValuePair<string, string> item in sd5)
{
Console.WriteLine("键名:" + item.Key + " 键值:" + item.Value);
}
Console.Read();