【C#】list 去重(转载)
Enumerable.Distinct 方法 是常用的LINQ扩展方法,属于System.Linq的Enumerable方法,可用于去除数组、集合中的重复元素,还可以自定义去重的规则。
转载来源:https://www.cnblogs.com/Robert-go-go/p/5399198.html
有两个重载方法:

//
// 摘要:
// 通过使用默认的相等比较器对值进行比较返回序列中的非重复元素。
//
// 参数:
// 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);
}
}

使用不到参数的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));
}
}

调用:
list.MyDistinct(s=>s.Id).ToList().ForEach(s => Console.WriteLine(s.ToString()));
用到了泛型、委托、扩展方法等知识点。可以用于任何集合的各种去重场景
同理:C# List 集合 交集、并集、差集、去重,都是实现接口IEqualityComparer
https://www.cnblogs.com/hao-1234-1234/p/10408602.html
【C#】list 去重(转载)的更多相关文章
- list去重 转载
http://blog.csdn.net/huaishuming/article/details/47778319 1. 单个List 去重: 如果用的是Set集合就不用怕重复的问题了,如果用的Lis ...
- 使用SimHash进行海量文本去重[转载]
阅读目录 1. SimHash与传统hash函数的区别 2. SimHash算法思想 3. SimHash流程实现 4. SimHash签名距离计算 5. SimHash存储和索引 6. SimHas ...
- C#大数据文本高效去重
C#大数据文本高效去重 转载请注明出处 http://www.cnblogs.com/Huerye/ TextReader reader = File.OpenText(@"C:\Users ...
- 基于Redis的Bloomfilter去重(转载)
转载:http://blog.csdn.net/bone_ace/article/details/53107018 前言 “去重”是日常工作中会经常用到的一项技能,在爬虫领域更是常用,并且规模一般都比 ...
- C# MVC 用户登录状态判断 【C#】list 去重(转载) js 日期格式转换(转载) C#日期转换(转载) Nullable<System.DateTime>日期格式转换 (转载) Asp.Net MVC中Action跳转(转载)
C# MVC 用户登录状态判断 来源:https://www.cnblogs.com/cherryzhou/p/4978342.html 在Filters文件夹下添加一个类Authenticati ...
- 【转载】C#中通过Distinct方法对List集合进行去重
在C#的List集合对象中,可以使用Distinct方法来对List集合元素进行去重,如果list集合内部元素为值类型,则Distinct方法根据值类型是否相等来判断去重,如果List集合内部元素为引 ...
- [转载]基于Redis的Bloomfilter去重(附Python代码)
前言: “去重”是日常工作中会经常用到的一项技能,在爬虫领域更是常用,并且规模一般都比较大.去重需要考虑两个点:去重的数据量.去重速度.为了保持较快的去重速度,一般选择在内存中进行去重. 数据量不大时 ...
- js 数组去重求和 (转载)
方法一:js数组id去重,value值相加问题 来源:https://www.jianshu.com/p/8f79e31b46ed // js let arr = [ { id: 1, value: ...
- js 数组 去重 算法(转载)
以下内容可能有重复部分,项目有用上,但还没来得急整理和验证. 一:https://www.cnblogs.com/jiayuexuan/p/7527055.html 1.遍历数组法 它是最简单的数组去 ...
随机推荐
- html基础知识梳理
1.浏览器内核 补充:blink为Google与Opera共同开发. 2.web标准 web标准为w3c和其他标准化组织制定的一系列标准的集合.(标签闭合.小写.不乱嵌套,使用外链css/js;结构行 ...
- TDD:什么是桩(stub)和模拟(mock)?
背景 本文假设你对TDD.Stub和Mock已经有了初步的认识,本文简单解释一下stub和mock的区别和使用场景,先看看他们之间的关系: 由上图可以知道mock框架可以非常容易的开发stub和moc ...
- 每天学点SpringCloud(十三):SpringCloud-Stream整合RabbitMQ
我们知道,当微服务越来越来多的时候,仅仅是feign的http调用方式已经满足不了我们的使用场景了.这个时候系统就需要接入消息中间件了.相比较于传统的Spring项目.SpringBoot项目使用消息 ...
- Docker学习笔记-Docker for Windows 安装
前言: 环境:windows10专业版 64位 正文: 官方下载地址:https://hub.docker.com/editions/community/docker-ce-desktop-windo ...
- table-layout引起的探索——fixed和auto的区别
问题:最近想把mui提供的底部导航组件样式单独抽出来,遇到一个问题:给底部图片下的文字设置了超出隐藏,但没有生效,如下图: 注:该底部导航为mui提供的组件 解决:这让我百思不得其解,经过一些琢磨后发 ...
- oo第二单元的自白
电梯第一次作业 第一次电梯较为简单,主要目的在于初步接触多线程,可以实现一些简单的操作. 在本次作业中,为了更好的了解多线程,我也阅读了一些代码,并据此仿写完成了第一次作业. 根据生产者和消费者的模式 ...
- 机器学习入门05 - 泛化 (Generalization)
原文链接:https://developers.google.com/machine-learning/crash-course/generalization 泛化是指模型很好地拟合以前未见过的新数据 ...
- [EXP]Microsoft Windows 10 (Build 17134) - Local Privilege Escalation (UAC Bypass)
#include "stdafx.h" #include <Windows.h> #include "resource.h" void DropRe ...
- Mac idea激活
感谢https://blog.csdn.net/HALEN001/article/details/81137092 1.下载IntelliJ IDEA 2018.2.2版本和破解补丁Jetbrains ...
- 使用C# (.NET Core) 实现简单工厂(Simple Factory) 和工厂方法设计模式 (Factory Method Pattern)
本文源自深入浅出设计模式. 只不过我是使用C#/.NET Core实现的例子. 前言 当你看见new这个关键字的时候, 就应该想到它是具体的实现. 这就是一个具体的类, 为了更灵活, 我们应该使用的是 ...