You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取两个List<int[]>的交集?Linq Intersect返回空的问题

问题原因

int[]是引用类型,Linq的Intersect方法默认使用引用相等性判断——只有当两个数组是内存中的同一个对象时,才会被判定为相等。你例子里的两个{1,1,1}数组是独立创建的不同对象,所以默认的Intersect无法识别它们是交集元素。而int是值类型,默认比较的是值本身,所以List<int>可以正常用Intersect取交集。

解决方案

有两种常用的解决思路:

方法一:用Where+SequenceEqual直接比较内容

通过遍历list1的每个元素,检查list2中是否存在内容完全相同的数组:

List<int[]> intersection = list1.Where(arr1 => list2.Any(arr2 => arr1.SequenceEqual(arr2))).ToList();

这种方式实现简单,但如果两个列表的元素数量较多,时间复杂度是O(n*m),性能会比较差。

方法二:自定义相等比较器(推荐大数据量场景)

实现一个IEqualityComparer<int[]>,让Intersect根据数组内容判断相等性:

1. 定义比较器类

public class IntArrayEqualityComparer : IEqualityComparer<int[]>
{
    public bool Equals(int[] x, int[] y)
    {
        // 处理null情况
        if (x == null || y == null)
            return x == y;
        // 用SequenceEqual比较数组内容
        return x.SequenceEqual(y);
    }

    public int GetHashCode(int[] obj)
    {
        if (obj == null)
            return 0;
        // 生成基于数组内容的哈希码
        int hash = 17;
        foreach (int num in obj)
        {
            hash = hash * 31 + num.GetHashCode();
        }
        return hash;
    }
}

2. 在Intersect中使用比较器

List<int[]> intersection = list1.Intersect(list2, new IntArrayEqualityComparer()).ToList();

这种方式下Intersect会利用哈希表优化查找,时间复杂度为O(n+m),适合元素较多的场景。

内容的提问来源于stack exchange,提问作者romato

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 07:22:45