关键词:C#  List 集合 交集、并集、差集、去重, 对象集合、 对象、引用类型、交并差、List<T>

有时候看官网文档是最高效的学习方式!

一、简单集合

Intersect 交集,Except 差集,Union 并集
int[] oldArray = { 1, 2, 3, 4, 5 };
int[] newArray = { 2, 4, 5, 7, 8, 9 };
var jiaoJi = oldArray.Intersect(newArray).ToList();//2,4,5
var oldChaJi = oldArray.Except(newArray).ToList();//1,3
var newChaJi = newArray.Except(oldArray).ToList();//7,8,9
var bingJi = oldArray.Union(newArray).ToList();//1,2,3,4,5,7,8,9

二、对象集合

Product[] store1 = {
new Product { Name = "apple", Code = },
new Product { Name = "orange", Code = }
}; Product[] store2 = {
new Product { Name = "apple", Code = },
new Product { Name = "lemon", Code = }
}; IEnumerable<Product> union =store1.Union(store2,new ProductComparer());
IEnumerable<Product> except=store1.Except(store2,new ProductComparer());
IEnumerable<Product> intersect=store1.Intersect(store2,new ProductComparer());
IEnumerable<Product> distinct=store1.Distinct(store2,new ProductComparer());

小提示:

1:IEnumerable<Product> 可以简化为 匿名类型 var
对自己去重:
var distinct=store1.Distinct(new ProductComparer());
相对于别人去重
var distinct=store1.Distinct(store2,new ProductComparer());
2: 可以继续进行一些linq或拉姆达操作
 var distinct=store1.Distinct(store2,new ProductComparer()).OrderBy(c=>c.Code);
原因是引用了linq组件:using System.Linq;

三、比较类的实现
public class Product
{
public string Id {get;set}
public string Name { get; set; }
public int Code { get; set; }
}

 1只有一个比较条件

//如果对象存在唯一主键,例如:从数据库里查询出来的数据存在 ID

class ProductComparer : IEqualityComparer<Product>
{
// Products are equal if their names and product numbers are equal.
public bool Equals(Product x, Product y)
{ //Check whether the compared objects reference the same data.
if (Object.ReferenceEquals(x, y)) return true; //Check whether any of the compared objects is null.
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false; //Check whether the products' properties are equal.
return x.ID == y.ID;
} // If Equals() returns true for a pair of objects
// then GetHashCode() must return the same value for these objects. public int GetHashCode(Product product)
{
//Check whether the object is null
if (Object.ReferenceEquals(product, null)) return ; //Get hash code for the Code field.
int hashID = product.ID.GetHashCode(); //Calculate the hash code for the product.
return hashID;
} }

2 多个比较条件

// 如果存在组合主键或组合唯一索引,即多个字段组合才能确定唯一性。
// Custom comparer for the Product class
class ProductComparer : IEqualityComparer<Product>
{
// Products are equal if their names and product numbers are equal.
public bool Equals(Product x, Product y)
{ //Check whether the compared objects reference the same data.
if (Object.ReferenceEquals(x, y)) return true; //Check whether any of the compared objects is null.
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false; //Check whether the products' properties are equal.
return x.Code == y.Code && x.Name == y.Name;
} // If Equals() returns true for a pair of objects
// then GetHashCode() must return the same value for these objects. public int GetHashCode(Product product)
{
//Check whether the object is null
if (Object.ReferenceEquals(product, null)) return ; //Get hash code for the Name field if it is not null.
int hashProductName = product.Name == null ? : product.Name.GetHashCode(); //Get hash code for the Code field.
int hashProductCode = product.Code.GetHashCode(); //Calculate the hash code for the product.
return hashProductName ^ hashProductCode;
} }

3 难道我们每次都要“简单重复的”继承IEqualityComparer接口,来重新实现一个“几乎完全相同的”的Compare类吗?

对于只有一个比较条件的简单情况,我们可以直接对 Distinct、Union、Except、Intersect 进行封装,简单通用方法:

来源:C#list去重, https://www.cnblogs.com/hao-1234-1234/p/8855218.html

    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));
}
}
然后这么使用:store1.MyDistinct(s=>s.Id).ToList();
Id 是用于较的属性(或字段),它是可以是任何一个属性。
4、多个比较条件 的通用方法如何实现?
类似于 store1.MyDistinct(s=>s.Id&&Name).ToList();

四、微软官方文档

union :https://docs.microsoft.com/zh-cn/dotnet/api/system.linq.enumerable.union?view=netframework-4.8

intersect:https://docs.microsoft.com/zh-cn/dotnet/api/system.linq.enumerable.intersect?view=netframework-4.8

except:https://docs.microsoft.com/zh-cn/dotnet/api/system.linq.enumerable.except?view=netframework-4.8

distinct:https://docs.microsoft.com/zh-cn/dotnet/api/system.linq.enumerable.distinct?view=netframework-4.8

合交并差 核心代码是相同的: IEqualityComparer 。

建议在看看文档其它部分,以备后用,文档写的很棒!

例如:join 某些情况与union等效。

五、交集、并集、差集、补集、对称差集 示意图,

后两者后可以有前三者演变而来。补集可以求差或去重、对称差集可以先求差、在求并;

参考过的文章

https://www.oschina.net/code/snippet_222150_16997

http://www.cnblogs.com/flywing/p/5912242.html

https://blog.csdn.net/wizblack/article/details/78796557

C# List 集合 交集、并集、差集、去重, 对象集合、 对象、引用类型、交并差补、List<T>的更多相关文章

  1. js求对象数组的交集/并集/差集/去重

    1.求交集 var arr1 = [{name:'name1',id:1},{name:'name2',id:2},{name:'name3',id:3}]; var arr1Id = [1,2,3] ...

  2. js Array 交集 并集 差集 去重

    最劲项目需要用到js数组去重和交集的一些运算,我的数组元素个数可能到达1000以上,网上的实现方式都是2次循环,性能不适合我的需求,1000*1000那循环次数太多了,所以我这里采用对象object来 ...

  3. 【转】 js数组 Array 交集 并集 差集 去重

    原文:http://blog.csdn.net/ma_jiang/article/details/52672762 最劲项目需要用到js数组去重和交集的一些运算,我的数组元素个数可能到达1000以上, ...

  4. LINQ交集/并集/差集/去重

    using System.Linq; List<string> ListA = new List<string>(); List<string> ListB = n ...

  5. js求两个数组的交集|并集|差集|去重

    let a = [1,2,3], b= [2, 4, 5]; 1.差集 (a-b 差集:属于a但不属于b的集合)  a-b = [1,3] (b-a 差集:属于b但不属于a的集合)  b-a = [4 ...

  6. 如何求ArrayList集合的交集 并集 差集 去重复并集

    需要用到List接口中定义的几个方法: addAll(Collection<? extends E> c) :按指定集合的Iterator返回的顺序将指定集合中的所有元素追加到此列表的末尾 ...

  7. java 两个list 交集 并集 差集 去重复并集

    前提需要明白List是引用类型,引用类型采用引用传递. 我们经常会遇到一些需求求集合的交集.差集.并集.例如下面两个集合: List<String> list1 = new ArrayLi ...

  8. (java/javascript) list 交集 并集 差集 去重复并集

    java list 交集 并集 差集 去重复并集 package com; import java.util.ArrayList; import java.util.Iterator; import ...

  9. Python 求两个文本文件以行为单位的交集 并集 差集

    Python 求两个文本文件以行为单位的交集 并集 差集,来代码: s1 = set(open('a.txt','r').readlines()) s2 = set(open('b.txt','r') ...

  10. spark之交集并集差集拉链

    spark之交集并集差集拉链 def main(args: Array[String]): Unit = { val sparkConf = new SparkConf().setMaster(&qu ...

随机推荐

  1. Redis安装及使用

    1.我们可以通过在官网下载tar.gz的安装包,或者通过wget的方式下载 进入要下载到的文件夹: wget http://download.redis.io/releases/redis-4.0.1 ...

  2. js面向对象和php面向对象的区别

    ---恢复内容开始--- js的面向对象 1.类 具体相同的特征的一些对象的集合. 2.对象 具体到某一个失误了都可以叫做对象. 3.类  通过function 定义类  所以在js里类的本质是函数, ...

  3. npm修改淘宝原

    //修改之前查看一下npm config get registry https://registry.npmjs.org/ //设置源npm config set registry https://r ...

  4. python—迭代器、生成器

    1.迭代器(iteration) 迭代器协议:提供next()方法,该方法要么返回迭代的下一项,要么异常.(只能往后走) 可迭代对象:实现迭代器协议的对象. **字符串.列表.元祖.字典.集合.文件都 ...

  5. 1.3 History of Android Plug-in Programing

          In July 27, 2012 , it was the first milestone in Android plug-in technology. Yimin Tu(mmin18 o ...

  6. 微服务架构-选择Spring Cloud,放弃Dubbo

    Spring Cloud 在国内中小型公司能用起来吗?从 2016 年初一直到现在,我们在这条路上已经走了一年多. 在使用 Spring Cloud 之前,我们对微服务实践是没有太多的体会和经验的.从 ...

  7. 深入理解Spring Redis的使用 (七)、Spring Redis 使用 jackson序列化 以及 BaseDao代码

    之前在介绍Spring Redis进行存储的时候,都是通过RedisTemplate中的defaultSerializer,即JdkSerializationRedisSerializer.通过Jdk ...

  8. [Swift]LeetCode437. 路径总和 III | Path Sum III

    You are given a binary tree in which each node contains an integer value. Find the number of paths t ...

  9. [Swift]LeetCode710. 黑名单中的随机数 | Random Pick with Blacklist

    Given a blacklist B containing unique integers from [0, N), write a function to return a uniform ran ...

  10. Xamarin.Android 集成百度地图SDK

    前言:趁着周六闲得没事干,赶紧搞一搞Xamarin,最近也是怪无聊的,枯燥的生活不如打几行代码带劲:好了我们进入正题 我这篇文章时参考一位大佬的博客进行改变的,当然他写的需要一定的经验才可以看得懂,我 ...