您的位置:首页 > 编程语言 > C#

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

2019-01-17 14:24 375 查看

转载自诗人江湖老,原文地址

  在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();
  • 1
[/code]

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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: