Hi how can i compare to array in C# ? i use this code but it`s result is false (must be true) ?
Array.Equals(childe1,grandFatherNode)
You can use Enumerable.SequenceEqual method:
static void Main(string[] args)
{
var a1 = new int[] { 1, 2, 3 };
var a2 = new int[] { 1, 2, 3 };
var a3 = new int[] { 1, 2, 4 };
var x = a1.SequenceEqual(a2); // true
var y = a1.SequenceEqual(a3); // false
}
Hope it helps,
Mitja
One more thing:
The elements are probably structs, but the array derives from System.Array, which is a reference type. That why Equals "fails".
As a practical and simple solution use IEnumerable<T>.SequenceEquals:
using System.Linq;
//...
//in some method:
bool bChecking = CheckArrays();
private bool CheckArrays()
{
string[] A = new string[4] { "A", "B", "C" };
string[] B = new string[4] { "A", "B", "D" };
return A.SequenceEqual(B); //return will be false!
}
Mitja
Hi
my arrays is Multidimensional and this method not work on this tyoe of arrays !
I did my own code for comparing multidimensional array. And it works, at least as far as I was testing. Let me know what you thing:
bool bIsEqual = true;
string[,] array1 = new string[,] { { "A", "B" }, { "C", "D" } };
string[,] array2 = new string[,] { { "A", "E" }, { "C", "D" } };
for (int i = 0; i < array1.GetLength(0); i++)
{
int loop2 = 0;
if (!bIsEqual)
break;
for (int j = 0; j < array2.GetLength(0); j++)
{
loop2++;
string A = array1[i, j];
string B = array2[i, j];
if (A != B)
{
bIsEqual = false;
break;
}
if (loop2 == 2)
break;
}
}
if (!bIsEqual)
Console.WriteLine("Arrays are not equal");
else
Console.WriteLine("Arrays are equal");
Console.ReadLine();
Mitja
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.