C# 集合交、并、差、去重,对象集合交并差

关键词: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 = 9 }, 
     new Product { Name = "orange", Code = 4 } 
};

Product[] store2 = {
     new Product { Name = "apple", Code = 9 }, 
     new Product { Name = "lemon", Code = 12 }
 };

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(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 Name { get; set; }
    public int Code { get; set; }
}

 核心代码:简单情况

//如果对象存在唯一主键,例如:从数据库里查询出来的数据存在 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 0;


        //Get hash code for the Code field.
        int hashID = product.ID.GetHashCode();

        //Calculate the hash code for the product.
        return hashID;
    }

}

核心代码:复杂情况

// 如果存在组合主键或组合唯一索引,即多个字段组合才能确定唯一性。
// 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 0;

        //Get hash code for the Name field if it is not null.
        int hashProductName = product.Name == null ? 0 : 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;
    }

}

 

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

 三、微软官方文档

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

 

转载于:https://www.cnblogs.com/hao-1234-1234/p/10408602.html

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C# 中可以使用 Linq 的 Distinct 方法进行集合去重,但是默认情况下 Distinct 只能根据元素的值进行比较,无法根据多个字段进行比较。 要实现多字段去重,可以使用 Linq 的 GroupBy 方法先按照指定字段进行分组,然后再取每组的第一个元素,即可实现多字段去重。 示例代码如下: ```csharp class Person { public string Name { get; set; } public int Age { get; set; } public string Address { get; set; } } List<Person> persons = new List<Person> { new Person { Name = "Tom", Age = 18, Address = "Beijing" }, new Person { Name = "Jack", Age = 20, Address = "Shanghai" }, new Person { Name = "Tom", Age = 18, Address = "Beijing" }, new Person { Name = "Tom", Age = 22, Address = "Shenzhen" }, new Person { Name = "Mike", Age = 20, Address = "Shanghai" } }; var distinctPersons = persons.GroupBy(p => new { p.Name, p.Age, p.Address }) .Select(g => g.First()) .ToList(); ``` 上述代码中,首先定义了一个 Person 类,包含了三个字段:Name、Age 和 Address。然后创建了一个包含了几个 Person 对象的 List。 接下来使用 Linq 的 GroupBy 方法将 Person 对象按照 Name、Age 和 Address 进行分组,得到一个键值对集合,其中键为一个包含三个字段的匿名类型对象,值为该分组下的所有 Person 对象。然后使用 Select 方法取每个分组的第一个元素,即可得到去重后的 Person 集合。最后通过 ToList 方法将结果转换为 List。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值