【发布时间】:2019-12-06 17:21:32
【问题描述】:
我有两个二维数组列表
List<double[,]>list1=new List<double[4,4]>();
List<double[,]>list2=new List<double[4,4]>();
列表的长度不一定相等。
【问题讨论】:
我有两个二维数组列表
List<double[,]>list1=new List<double[4,4]>();
List<double[,]>list2=new List<double[4,4]>();
列表的长度不一定相等。
【问题讨论】:
您所拥有的内容不起作用,因为Contains 将在迭代列表时进行引用比较以检查相等性。除非您在每个列表中的二维数组引用相同的对象引用,否则即使它们在语义上相同,也不会将它们标识为相等。
例如,在这种情况下会找到匹配项:
var my2d = new double[2, 2] { { 1, 3 }, { 3, 5 } };
List<double[,]> list1 = new List<double[,]>() { my2d };
List<double[,]> list2 = new List<double[,]>() { my2d };
foreach (var matrix in list1)
if (list2.Contains(matrix))
Console.WriteLine("FOUND!");
但是,如果我们将列表更改为具有二维数组的单独实例,则不会:
List<double[,]> list1 = new List<double[,]>() { new double[2, 2] { { 1, 3 }, { 3, 5 } } };
List<double[,]> list2 = new List<double[,]>() { new double[2, 2] { { 1, 3 }, { 3, 5 } } };
您可以克服这个问题的一种方法是指定您自己的IEqualityComparer 来告诉Contains 方法如何执行比较。例如,这里有一个可以逐个元素比较二维数组的东西:
public class TwoDimensionCompare<T> : IEqualityComparer<T[,]>
{
public bool Equals(T[,] x, T[,] y)
{
// fail fast if the sizes aren't the same
if (y.GetLength(0) != x.GetLength(0)) return false;
if (y.GetLength(1) != x.GetLength(1)) return false;
// compare element by element
for (int i = 0; i < y.GetLength(0); i++)
for (int z = 0; z < y.GetLength(1); z++)
if (!EqualityComparer<T>.Default.Equals(x[i, z], y[i, z])) return false;
return true;
}
public int GetHashCode(T[,] obj)
{
return obj.GetHashCode();
}
}
用法:
List<double[,]> list1 = new List<double[,]>() { new double[2, 2] { { 1, 3 }, { 3, 5 } } };
List<double[,]> list2 = new List<double[,]>() { new double[2, 2] { { 1, 3 }, { 3, 5 } } };
foreach (var matrix in list1)
if (list2.Contains(matrix, new TwoDimensionCompare<double>()))
Console.WriteLine("FOUND!");
【讨论】: