Yura G
Yura G

Reputation: 626

How to compare multidimensional arrays in C#?

How to compare multidimensional arrays? Just true/false.

    double[,] data1 = new double[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };    
    double[,] data2 = new double[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
    
    //bool compare = data1.SequenceEqual(data2);

Is there way to compare 2d arrays like 1d array ?

    data1.SequenceEqual(data2);     

I have to compare every second, so easiest way will be great. Thanks a lot.

Upvotes: 31

Views: 20889

Answers (4)

user287107
user287107

Reputation: 9417

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>());

Upvotes: 35

Soleil
Soleil

Reputation: 7287

A generic extension method to compare 2D arrays:

public static bool SequenceEquals<T>(this T[,] a, T[,] b) => a.Rank == b.Rank
    && Enumerable.Range(0, a.Rank).All(d=> a.GetLength(d) == b.GetLength(d))
    && a.Cast<T>().SequenceEqual(b.Cast<T>());

Upvotes: 4

hdev
hdev

Reputation: 6517

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, 

Upvotes: 3

Afif Lamloumi
Afif Lamloumi

Reputation: 1

You can do this

data1.SequenceEqual(data2);  

Upvotes: -8

Related Questions