问题
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.
回答1:
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>());
回答2:
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,
回答3:
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;
}
}
}
回答4:
You can do this
data1.SequenceEqual(data2);
来源:https://stackoverflow.com/questions/12446770/how-to-compare-multidimensional-arrays-in-c-sharp