OrderBy排序和IComparer的使用

一,OrderBy排序在MDSN中有两种使用方法,如下

 

1》第一种方法的使用,就是根据某个字段排序,使用默认的比较器(Comparer<T>.default),如下,由于Dictionary是继承IEnumerable的,所以这里可以使用Dictionary作为排序集合,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("B", "2");
            dic.Add("A", "1");
            dic.Add("D", "4");
            dic.Add("C", "3");
            StringBuilder str1 = new StringBuilder();
            var param1 = dic.OrderBy(x => x.Key).ToDictionary(x => x.Key, y => y.Value);
            foreach (string dic1 in param1.Keys)
            {
                str1.Append(dic1+",");
            }
            Console.WriteLine(str1.ToString());
            Console.ReadKey();
        }
    }
}

2》第二种方法的使用,按使用指定的比较器按升序对序列的元素进行排序。如下(使用ASCII值排序的例子介绍)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("B", "2");
            dic.Add("A", "1");
            dic.Add("D", "4");
            dic.Add("C", "3");
            StringBuilder str1 = new StringBuilder();
            var param = dic.OrderBy(x => x.Key, new ComparerTest()).ToDictionary(x => x.Key, y => y.Value);
            foreach (string dic1 in param.Keys)
            {
                str1.Append(dic1);
            }
            Console.WriteLine(str1.ToString());
            Console.ReadKey();
        }
    }
    public class ComparerTest : IComparer<String>
    {
        public int Compare(String x, String y)
        {
            return string.CompareOrdinal(x, y);
        }
    }
}

 看下面这句的代码,不知道,大家有没有跟我一样的疑惑?如下

var param = dic.OrderBy(x => x.Key, new ComparerTest()).ToDictionary(x => x.Key, y => y.Value);

为什么这句话实例ComparerTest这个类就可以完成比较???

查询一遍第二个方法的源码,如下图

1,原来指定的比较器接收的是IComparer<TKey> comparer类型,而ComparerTest是继承 IComparer<TKey>实现的比较方法。

2,相当于IComparer<String> icomparer = new ComparerTest();(这里是显式转换和隐式,想了解可以看http://www.cnblogs.com/May-day/p/6856457.html),这里实现了IComparer中的Compare方法

3,最后OrderBy调用比较器,即是IComparer中的Compare,排序

 

转载于:https://www.cnblogs.com/May-day/p/7490334.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值