Linq Enumerable.Distinct方法去重
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方法去重的更多相关文章
- 【C#】详解使用Enumerable.Distinct方法去重
Enumerable.Distinct 方法 是常用的LINQ扩展方法,属于System.Linq的Enumerable方法,可用于去除数组.集合中的重复元素,还可以自定义去重的规则. 有两个重载方法 ...
- Linq的Distinct方法的扩展
原文地址:如何很好的使用Linq的Distinct方法 Person1: Id=1, Name="Test1" Person2: Id=1, Name="Test1&qu ...
- 如何很好的使用Linq的Distinct方法
Person1: Id=1, Name="Test1" Person2: Id=1, Name="Test1" Person3: Id=2, Name=&quo ...
- 扩展Linq的Distinct方法动态根据条件进行筛选
声明为了方便自己查看所以引用 原文地址:http://www.cnblogs.com/A_ming/archive/2013/05/24/3097062.html Person1: Id=1, Nam ...
- Linq 中 Distinct 方法扩展
原文链接 http://www.cnblogs.com/A_ming/archive/2013/05/24/3097062.html public static class LinqEx { publ ...
- 【转载】C#中通过Distinct方法对List集合进行去重
在C#的List集合对象中,可以使用Distinct方法来对List集合元素进行去重,如果list集合内部元素为值类型,则Distinct方法根据值类型是否相等来判断去重,如果List集合内部元素为引 ...
- Core源码(二) Linq的Distinct扩展
先贴源码地址 https://github.com/dotnet/corefx/tree/master/src/System.Linq/src .NET CORE很大一个好处就是代码的开源,你可以详细 ...
- 如何使用Linq或EF来对数据去重——Distinct方法详解
刚开始接触LINQ时使用distinct去重时和大家一样遇到了一些麻烦,很感谢 http://www.cnblogs.com/A_ming/archive/2013/05/24/3097062.htm ...
- 整理一下 System.Linq.Enumerable 类中的那些比较少用的方法
Linq 虽然用得多,但是里面有一些方法比较少用,因此整理一下.Enumerable 类的所有方法可以在 MSDN 上查阅到:https://msdn.microsoft.com/zh-cn/libr ...
随机推荐
- BZOJ1067&P2471 [SCOI2007]降雨量[线段树裸题+细节注意]
dlntqlwsl 很裸的一道线段树题,被硬生生刷成了紫题..可能因为细节问题吧,我也栽了一次WA50分.不过这个隐藏条件真的对本菜鸡来说不易发现啊. 未知的年份连续的就看成一个就好了,把年份都离散化 ...
- element el-input 自动获取焦点和IE下光标位置解决方法
在实际开发中我们经常会碰到这样的场景,就是有input的地方都喜欢切换过去input自动获取焦点. 如果这个问题是在input中,很容易就实现了,但是element里面的el-input看源码,其实不 ...
- Vijos:P1234口袋的天空
背景 小杉坐在教室里,透过口袋一样的窗户看口袋一样的天空. 有很多云飘在那里,看起来很漂亮,小杉想摘下那样美的几朵云,做成棉花糖. 描述 给你云朵的个数N,再给你M个关系,表示哪些云朵可以连在一起. ...
- HDU4027(线段树单点更新区间)
Can you answer these queries? Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65768/65768 K ...
- Day07:常用模块,面向对象编程(对象&类)及内置函数
今日内容:1.常用模块2.面向对象编程(*****) 介绍面向对象编程 类 对象3.内置函数------------------------------1.面向过程编程 核心“ ...
- 1.改变项目 动态库、静态库属性。 2.使用运行库 /MD、/MT、/LD说明
/MD./MT./LD(使用运行库) 有关 C 运行库以及使用 /clr(公共语言运行时编译) 进行编译时要使用哪些库的更多信息,请参见 CRT 库功能. 传递给链接器的给定调用的所有模块都必须使用相 ...
- PDF,IMAGE,HTML,WORD,EXCEL 互操作
http://www.cnblogs.com/lyl6796910/p/3318056.html
- Arduino 元件
http://www.rs-online.com/designspark/electronics/
- oracle 日期问题 网上找到自己查阅时方便
第一部分:oracle sql日期比较: oracle sql日期比较:在今天之前: select*from up_date whereupdate< to_date('2007-09-07 0 ...
- unite2017相关
日程 http://unite2017.csdn.net/ http://www.sohu.com/a/137202360_280780 http://www.gameres.com/750046.h ...