Dictionary<K,V>正反排序方法总结

Dictionary排序,用到的函数就两个:

正序:Enumerable.OrderBy<TSourceTKey>(IEnumerable<TSource>, Func<TSource, TKey>)

反序:Enumerable.OrderByDescending<TSourceTKey>(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();


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值