1

I have two float[] objects. Without writing a for-loop, I want to compare my two 1D arrays to see if they are equal numerically or not.

When I run the following code (as all elements are equal), it doesn't go through the if-statement and show the message.

How should I apply the Equals command to work properly?
Is there any compare-command I could use?

 Random r1 = new Random(1);
   int rndNumber= r1.Next(10);
   float[] m = Enumerable.Repeat((float)rndNumber, 180).ToArray();
   float[] m2 = Enumerable.Repeat((float)rndNumber, 180).ToArray();
   if (m.Equals(m2))
    {
    MessageBox.Show("we are equal");
   }
Servy
  • 202,030
  • 26
  • 332
  • 449
farzin parsa
  • 537
  • 2
  • 9
  • 33

1 Answers1

8

The Equal method for Array isn't overridden from the default object implementation that just compares the references of the objects (which aren't equal).

You want to compare the values of each element in the sequence, and ensure it has the same content in the same order. To do that, use SequenceEqual in System.Linq.Enumerable.

if(m.SequenceEqual(m2)) {...}

Internally that method will iterate through each element of each sequence and call Equals on each element pair to verify that they are all the same. While this is certainly easier (and arguably more readable) to use than a for loop, keep in mind that it will perform no better than using a for loop, it's just hiding the loop from you.

Servy
  • 202,030
  • 26
  • 332
  • 449