Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-apps-script/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何检查列表中是否存在二维数组?_C#_List_Arraylist - Fatal编程技术网

C# 如何检查列表中是否存在二维数组?

C# 如何检查列表中是否存在二维数组?,c#,list,arraylist,C#,List,Arraylist,我有两个二维数组的列表 List<double[,]>list1=new List<double[4,4]>(); List<double[,]>list2=new List<double[4,4]>(); list1=新列表(); list2=新列表(); 列表的长度不一定相等。您拥有的内容不起作用,因为包含的内容将在迭代列表时进行引用比较以检查是否相等。除非每个列表中的2d数组引用相同的对象引用,否则即使它们在语义上相同,也不会将它们标识为

我有两个二维数组的列表

List<double[,]>list1=new List<double[4,4]>();
List<double[,]>list2=new List<double[4,4]>();
list1=新列表();
list2=新列表();

列表的长度不一定相等。

您拥有的内容不起作用,因为
包含的内容将在迭代列表时进行引用比较以检查是否相等。除非每个列表中的2d数组引用相同的对象引用,否则即使它们在语义上相同,也不会将它们标识为相等

例如,在这种情况下,将找到匹配项:

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 } } };

foreach (var matrix in list1)
    if (list2.Contains(matrix, new TwoDimensionCompare<double>())) 
        Console.WriteLine("FOUND!");
list1=newlist(){newdouble[2,2]{{{1,3},{3,5}};
List list2=new List(){new double[2,2]{{{1,3},{3,5}}};
foreach(列表1中的var矩阵)
if(list2.Contains(矩阵,新的二维比较())
控制台。WriteLine(“找到!”);
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!");