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> { , , , , , , ,  };
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);
}
}

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

            List<Student> list = new List<Student>() {
new Student("James",,"Basketball"),
new Student("James",,"Basketball"),
new Student("Kobe",,"Basketball"),
new Student("Curry",,"Football"),
new Student("Curry",,"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));
}
}

调用:

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

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

最新文章

  1. 【POJ 1390】Blocks
  2. 关于JDK 安装,以及Java环境的设置
  3. ISO9126软件质量模型
  4. JS高级程序设计2nd部分知识要点7
  5. iOS-事务相关
  6. [转]IIS上部署网站
  7. 工作记录8:iOS 传值问题总结(7种传值完美介绍)
  8. 洛谷P2402 奶牛隐藏(网络流,二分答案,Floyd)
  9. 【一天一道LeetCode】#10. Regular Expression Matching
  10. JavaWeb 过滤器——验证登录 防止未登录进入界面
  11. http基本get和post请求
  12. SPOJ RPLN (模板题)(ST算法)【RMQ】
  13. gogs 源码阅读笔记 001
  14. EasyUI treegrid 模糊查询、搜索
  15. codeforces round#510
  16. 正则表达式取querystring
  17. Android KITKAT 以上实现沉浸式状态栏
  18. 【P4语言学习】basic_routing.p4
  19. 工具IDEA 配置springboot+maven项目
  20. 20个专业H5(HTML5)动画工具推荐

热门文章

  1. 硬编码写RadioGroup的时候要注意设置RadioButton的Id
  2. PE File.
  3. 使用EMMET中的小坑
  4. Word 中标题的编号变成黑框
  5. ResultSetMetaData rsmd = rs.getMetaData()是什么意思?
  6. 获取C++类成员变量的地址偏移
  7. sicily-2499 平方数
  8. delegate 中的BeginInvoke和EndInvoke方法
  9. actionscript sendToURL请求url,传递http_referer分浏览器统计
  10. JDK环境变量配置贺Tomcat环境搭建