Enumerable.Distinct 方法 是常用的LINQ扩展方法,属于System.Linq的Enumerable方法,可用于去除数组、集合中的重复元素,还可以自定义去重的规则。

有两个重载方法:

        //
// 摘要:
// 通过使用默认的相等比较器对值进行比较返回序列中的非重复元素。
//
// 参数:
// source:
// 要从中移除重复元素的序列。
//
// 类型参数:
// TSource:
// source 中的元素的类型。
//
// 返回结果:
// 一个 System.Collections.Generic.IEnumerable<T>,包含源序列中的非重复元素。
//
// 异常:
// System.ArgumentNullException:
// source 为 null。
public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source);
//
// 摘要:
// 通过使用指定的 System.Collections.Generic.IEqualityComparer<T> 对值进行比较返回序列中的非重复元素。
//
// 参数:
// source:
// 要从中移除重复元素的序列。
//
// comparer:
// 用于比较值的 System.Collections.Generic.IEqualityComparer<T>。
//
// 类型参数:
// TSource:
// source 中的元素的类型。
//
// 返回结果:
// 一个 System.Collections.Generic.IEnumerable<T>,包含源序列中的非重复元素。
//
// 异常:
// System.ArgumentNullException:
// source 为 null。
public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source, IEqualityComparer<TSource> comparer);
 

第一个方法不带参数,第二个方法需要传一个System.Collections.Generic.IEqualityComparer<T>的实现对象

1.值类型元素集合去重

List<int> list = new List<int> { 1, 1, 2, 2, 3, 4, 5, 5 };
list.Distinct().ToList().ForEach(s => Console.WriteLine(s));

执行结果是:1 2 3 4 5

2.引用类型元素集合去重

首先自定义一个Student类

   public class Student
{
public string Name { get; private set; }
public int Id { get; private set; }
public string Hobby { get; private set; }
public Student(string name, int id, string hobby)
{
this.Name = name;
this.Id = id;
this.Hobby = hobby;
}
/// <summary>
/// 方便输出,重写ToString方法
/// </summary>
/// <returns></returns>
public override string ToString()
{
return string.Format("{0}\t{1}\t{2}", this.Name, this.Id, this.Hobby);
}
}
    public class Student
{
public string Name { get; private set; }
public int Id { get; private set; }
public string Hobby { get; private set; }
public Student(string name, int id, string hobby)
{
this.Name = name;
this.Id = id;
this.Hobby = hobby;
}
/// <summary>
/// 方便输出,重写ToString方法
/// </summary>
/// <returns></returns>
public override string ToString()
{
return string.Format("{0}\t{1}\t{2}", this.Name, this.Id, this.Hobby);
}
}

使用不到参数的Distinct方法去重

 
            List<Student> list = new List<Student>() {
new Student("James",1,"Basketball"),
new Student("James",1,"Basketball"),
new Student("Kobe",2,"Basketball"),
new Student("Curry",3,"Football"),
new Student("Curry",3,"Yoga")
};
list.Distinct().ToList().ForEach(s => Console.WriteLine(s.ToString()));
 

执行结果:

可见,并没有去除重复的记录。

不带comparer参数的Distinct方法是使用的IEqualityComparer接口的默认比较器进行比较的,对于引用类型,默认比较器比较的是其引用地址,程序中集合里的每一个元素都是个新的实例,引用地址都是不同的,所以不会被作为重复记录删除掉。

因此,我们考虑使用第二个重载方法。

新建一个类,实现IEqualityComparer接口。注意GetHashCode方法的实现,只有HashCode相同才会去比较

 
    public class Compare:IEqualityComparer<Student>
{
public bool Equals(Student x,Student y)
{
return x.Id == y.Id;//可以自定义去重规则,此处将Id相同的就作为重复记录,不管学生的爱好是什么
}
public int GetHashCode(Student obj)
{
return obj.Id.GetHashCode();
}
}
 

然后调用

list.Distinct(new Compare()).ToList().ForEach(s => Console.WriteLine(s.ToString()));

执行结果:

我们按照Id去给这个集合去重成功!

3.如何编写一个具有扩展性的去重方法

public class Compare<T, C> : IEqualityComparer<T>
{
private Func<T, C> _getField;
public Compare(Func<T, C> getfield)
{
this._getField = getfield;
}
public bool Equals(T x, T y)
{
return EqualityComparer<C>.Default.Equals(_getField(x), _getField(y));
}
public int GetHashCode(T obj)
{
return EqualityComparer<C>.Default.GetHashCode(this._getField(obj));
}
}
public static class CommonHelper
{
/// <summary>
/// 自定义Distinct扩展方法
/// </summary>
/// <typeparam name="T">要去重的对象类</typeparam>
/// <typeparam name="C">自定义去重的字段类型</typeparam>
/// <param name="source">要去重的对象</param>
/// <param name="getfield">获取自定义去重字段的委托</param>
/// <returns></returns>
public static IEnumerable<T> MyDistinct<T, C>(this IEnumerable<T> source, Func<T, C> getfield)
{
return source.Distinct(new Compare<T, C>(getfield));
}
}
    public class Compare<T, C> : IEqualityComparer<T>
{
private Func<T, C> _getField;
public Compare(Func<T, C> getfield)
{
this._getField = getfield;
}
public bool Equals(T x, T y)
{
return EqualityComparer<C>.Default.Equals(_getField(x), _getField(y));
}
public int GetHashCode(T obj)
{
return EqualityComparer<C>.Default.GetHashCode(this._getField(obj));
}
}
public static class CommonHelper
{
/// <summary>
/// 自定义Distinct扩展方法
/// </summary>
/// <typeparam name="T">要去重的对象类</typeparam>
/// <typeparam name="C">自定义去重的字段类型</typeparam>
/// <param name="source">要去重的对象</param>
/// <param name="getfield">获取自定义去重字段的委托</param>
/// <returns></returns>
public static IEnumerable<T> MyDistinct<T, C>(this IEnumerable<T> source, Func<T, C> getfield)
{
return source.Distinct(new Compare<T, C>(getfield));
}
}

调用:

list.MyDistinct(s=>s.Id).ToList().ForEach(s => Console.WriteLine(s.ToString()));

用到了泛型、委托、扩展方法等知识点。可以用于任何集合的各种去重场景

Linq Enumerable.Distinct方法去重的更多相关文章

  1. 【C#】详解使用Enumerable.Distinct方法去重

    Enumerable.Distinct 方法 是常用的LINQ扩展方法,属于System.Linq的Enumerable方法,可用于去除数组.集合中的重复元素,还可以自定义去重的规则. 有两个重载方法 ...

  2. Linq的Distinct方法的扩展

    原文地址:如何很好的使用Linq的Distinct方法 Person1: Id=1, Name="Test1" Person2: Id=1, Name="Test1&qu ...

  3. 如何很好的使用Linq的Distinct方法

    Person1: Id=1, Name="Test1" Person2: Id=1, Name="Test1" Person3: Id=2, Name=&quo ...

  4. 扩展Linq的Distinct方法动态根据条件进行筛选

    声明为了方便自己查看所以引用 原文地址:http://www.cnblogs.com/A_ming/archive/2013/05/24/3097062.html Person1: Id=1, Nam ...

  5. Linq 中 Distinct 方法扩展

    原文链接 http://www.cnblogs.com/A_ming/archive/2013/05/24/3097062.html public static class LinqEx { publ ...

  6. 【转载】C#中通过Distinct方法对List集合进行去重

    在C#的List集合对象中,可以使用Distinct方法来对List集合元素进行去重,如果list集合内部元素为值类型,则Distinct方法根据值类型是否相等来判断去重,如果List集合内部元素为引 ...

  7. Core源码(二) Linq的Distinct扩展

    先贴源码地址 https://github.com/dotnet/corefx/tree/master/src/System.Linq/src .NET CORE很大一个好处就是代码的开源,你可以详细 ...

  8. 如何使用Linq或EF来对数据去重——Distinct方法详解

    刚开始接触LINQ时使用distinct去重时和大家一样遇到了一些麻烦,很感谢 http://www.cnblogs.com/A_ming/archive/2013/05/24/3097062.htm ...

  9. 整理一下 System.Linq.Enumerable 类中的那些比较少用的方法

    Linq 虽然用得多,但是里面有一些方法比较少用,因此整理一下.Enumerable 类的所有方法可以在 MSDN 上查阅到:https://msdn.microsoft.com/zh-cn/libr ...

随机推荐

  1. Qt容器组件(一)之QGroupBox、QScrollArea、QToolBox、QTabWidget

    QT中有九种容器组件,分别是组合框QGroupBox.滚动区QScrollArea.工具箱QToolBox.选项卡QTabWidget.控件栈QWidgetStack.框架QFrame.组件QWidg ...

  2. final修饰变量

    final修饰基本类型变量 当使用final修饰基本类型变量时,不能对基本类型变量重新赋值,因此基本类型变量不能被改变 final修饰引用类型变量 当使用final修饰引用类型变量时,它保存的仅仅是一 ...

  3. python使用uuid生成唯一id或str

    介绍: UUID是128位的全局唯一标识符,通常由32字节的字符串表示. 使用: import uuid print uuid.uuid1() 14bfe806-f1c7-11e6-83b5-0680 ...

  4. 使用EA完成数据库设计

    开始重构之后对于EA的了解也逐渐增多,今天就总结一下如何使用EA完成对数据库的设计.下边的图分别是截自机房收费系统和牛腩新闻开发的数据库,因为我第一遍写的时候是在机房合作的时候,而后建立牛腩新闻发布系 ...

  5. 水题 等差数列HDU 5400 Arithmetic Sequence

    主要是要知道它对于等差数列的定义,单个数也可以作为等差数列且一定满足题意,另外就是要算清楚区间与区间的关系,考虑两大类情况,一种是d1区间和d2区间连在一起,另外一种情况就是其余情况. #includ ...

  6. cassandra迁移表数据

    cassandra的迁移表数据有2种方式,以keyspace名为mydb,table名为user为例子: 方法一:copy命令. 这种方式适合数据量较小的情况. 1.进入cqlsh,输入命令:COPY ...

  7. 用expressjs写RESTful API

    http://blog.csdn.net/kiwi_coder/article/details/36424671     用expressjs写RESTful API http://blog.csdn ...

  8. Hive安装&nbsp;&nbsp;&nbsp;&nbsp;…

    Hive安装 mysql使用主机(win7)上的mysql数据库,启动后,要关闭360和win7自带的防火墙,确保在虚拟机里能拼通主机********************************* ...

  9. Java之匿名类讲解

    参考https://blog.csdn.net/jiaotuwoaini/article/details/51542059 匿名类,正如名字一样在java中没有名字标识的类,当然了编译后还是会安排一个 ...

  10. MySQL写入中文乱码

    这点确实很迷,我的数据库属性确实设置了utf-8字符集,但写入中文还是乱码,后来是直接修改了全局配置才修改过来. 1.进入MySQL的本地安装路径,我的安装路径是"C:\Program Fi ...