How to compare multidimensional arrays in C# ?

前端 未结 4 898
伪装坚强ぢ
伪装坚强ぢ 2020-12-30 23:47

How to compare multidimensional arrays? Just true/false.

double[,] data1 = new double[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };    
double[,] data2 = ne         


        
相关标签:
4条回答
  • 2020-12-31 00:15

    you can also try to solve it with 2 for-loops and comparing them with the counters.

    maybe something like this?

    for(int counter1 = 0; counter1 < data1.GetLength(0); counter1++)
    {
       for(int counter2 = 0; counter2 < data2.GetLength(1); counter2++)
       {
          if(data1[counter1, counter2] == data2[counter1, counter2])
          {
             bool isEqual = true;
          }    
       }
    }      
    
    0 讨论(0)
  • 2020-12-31 00:20

    You can flat a multi-dimension array with .Cast<String>

    Console.WriteLine("2D Array");
    String[,] array2d = new String[,] { { "A1", "B1" }, { "A2", "B2" } };
    foreach(var s in array2d.Cast<String>())
        Console.Write(s + ", ");
    
    Console.WriteLine("\r\n3D Array");
    String[,] array3d = new String[,] { { "A1", "B1", "C1" }, { "A2", "B2", "C1" } };
    foreach (var s in array3d.Cast<String>())
        Console.Write(s + ", ");
    

    Output

    2D Array
    A1, B1, A2, B2, 
    3D Array
    A1, B1, C1, A2, B2, C1, 
    
    0 讨论(0)
  • 2020-12-31 00:26

    You can do this

    data1.SequenceEqual(data2);  
    
    0 讨论(0)
  • 2020-12-31 00:27

    A multidimensional array can be used in linq as one dimensional enumerable. You just need to check also for the length of all dimensions. This snippet should be enough:

    var equal =
        data1.Rank == data2.Rank &&
        Enumerable.Range(0,data1.Rank).All(dimension => data1.GetLength(dimension) == data2.GetLength(dimension)) &&
        data1.Cast<double>().SequenceEqual(data2.Cast<double>());
    
    0 讨论(0)
提交回复
热议问题