C# Linq 在两个列表之间相交<int[]>

问题描述 投票:0回答:2

我想得到下面两个列表的交集

List<int[]> list1 = new List<int[]>
{
    new int[] { 0, 0, 0, },
    new int[] { 1, 1, 1, }
};

List<int[]> list2 = new List<int[]>
{
    new int[] { 1, 1, 1, },
    new int[] { 2, 2, 2, }
};

但是当我尝试

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

路口返回空。当我用两个 List(不是数组)尝试这个精确的设置时,它按预期工作。 这是我第一次使用 Linq。我怎样才能得到这个十字路口?

c# arrays linq intersection
2个回答
1
投票

使用

Where()
Any()

的方法

您可以比较列表/数组的相等性以及继承

IEnumerable
的所有其他内容与
SequenceEqual

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

0
投票

用于检查相等性的默认比较器是引用比较。
此默认值不适合比较数组的内容。

您可以通过使用自定义比较器(派生自

IEqualityComparer
)来实现您需要的,它实际上比较数组的内容:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp1
{
    internal class Program
    {
        class MyComparer : IEqualityComparer<int[]>
        {
            public bool Equals(int[] item1, int[] item2)
            {
                return item1.SequenceEqual(item2);
            }

            public int GetHashCode(int[] item)
            {
                int hash = 1;
                foreach (var i in item) { hash *= i; }
                return hash;
            }
        }

        static void Main(string[] args)
        {
            List<int[]> list1 = new List<int[]>
            {
                new int[] { 0, 0, 0, },
                new int[] { 1, 1, 1, }
            };

            List<int[]> list2 = new List<int[]>
            {
                new int[] { 1, 1, 1, },
                new int[] { 2, 2, 2, }
            };

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

            foreach (var list in intersection)
            {
                Console.WriteLine("{0}", string.Join(", ", list));
            }
         }
    }
}

输出:

1, 1, 1

请注意,我对

GetHashCode
的实现只是您可能需要改进的一个微不足道的实现。

© www.soinside.com 2019 - 2024. All rights reserved.