C#实现 Linq 序列的Distinct—— IEnumerable<T>.Distinct<T>()——IEqualityComparer

简介

  在C#中使用List或者Collection的时候,我们经常需要使用到Distinct操作,但是微软默认提供的Distinct重载方法并不能满足我们的需求。这时候,我们就需要自己动手做一番工作了。

Distinct方法的重载

  Linq的Distinct的方法有如下一个重载版本:

public static IEnumerable<TSource> Distinc<TSource>(
    this IEnumerable<TSource> source,
    IEqualityComparer<TSource> comparer
)

  其中:
  类型参数
  TSource
    source中的元素类型;
  参数
  source
    类型: System.Collections.Generic.IEnumerable<TSource>
    要从中移除重复元素的序列
  comparer
    类型:System.Collections.Generic.IEqualityComparer<TSource>
    用于比较值的 IEqualityComparer<T>
  
  返回值
    类型:System.Collections.Generic.IEnumerable<TSource>
    一个 IEnumerable<T>,包含源序列中的非重复元素。
 

实现IEqualityComparer

  现在关键就是如何实现方法中的comparer 参数,我们希望做一个能够适用于各个类型的comparer,这样,我们就需要用到委托。
  好,话不多说,代码如下:

using System.Collections.Generic;

namespace MissTangProject.HelperClass
{
    public class ListComparer<T> : IEqualityComparer<T>
    {
        public delegate bool EqualsComparer<F>(F x, F y);

        public EqualsComparer<T> equalsComparer;

        public ListComparer(EqualsComparer<T> _euqlsComparer)
        {
            this.equalsComparer = _euqlsComparer;
        }

        public bool Equals(T x, T y)
        {
            if (null != equalsComparer)
            {
                return equalsComparer(x, y);
            }
            else
            {
                return false;
            }
        }

        public int GetHashCode(T obj)
        {
            return obj.ToString().GetHashCode();
        }
    }
}

使用Linq的Distinct方法

  假设我们有一个BoilerWorkerModel类,该类有一个code属性,使用方法如下:
  

List<BoilerWorkerModel> newList = _list1.Distinct(new ListComparer<BoilerWorkerModel>((p1, p2) => (p1.Code == p2.Code))).ToList();

  这样,我们就实现了能够适用于各个类型source的comparer了,可以随意的使用Linq的Distinct方法了!
  到这里,大功告成。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值