我想得到下面两个列表的交集
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
使用
Where()
和Any()
的方法
您可以比较列表/数组的相等性以及继承
IEnumerable
的所有其他内容与SequenceEqual
List<int[]> intersection = list1.Where(l1 => list2.Any(l2=> l1.SequenceEqual(l2))).ToList();
用于检查相等性的默认比较器是引用比较。
此默认值不适合比较数组的内容。
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
的实现只是您可能需要改进的一个微不足道的实现。