Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Equality in ObservableCollection

Tags:

c#

equality

wpf

I have a custom object which I have successfully overriden the Equals and HashCode function. Then I have 2 Observable Collections on which I initialise the exact same objects (but with different reference). So I have this code:

if (qObjects.Equals(qObjects2))
{
    Console.WriteLine("Arrays are equal");
}

which I am expecting to return true but returns false. You might say that I did something wrong with Equal and HashCode function. But this is the weird:

for (int i = 0; i < qObjects.Count(); i++)
{
    arraysIsEqual = qObjects[i].Equals(qObjects2[i]);

    if (!arraysIsEqual)
    {
        break;
    }
}

if (arraysIsEqual)
{
    Console.WriteLine("Arrays are equal");
}

The above code snippet returns true. So what I am missing here?

like image 478
BlackM Avatar asked Oct 22 '25 04:10

BlackM


1 Answers

When you are comparing collections with Equals, the ObservableCollection objects themselves will be compared. This obviously results in false, because the collection's class does not override Equals (it's inherited from Object so compares references). In order not to have to iterate objects yourself, you can use SequenceEqual method. (Confusingly not the SequenceEquals method).

if (qObjects.SequenceEqual(qObjects2)) {
   Console.WriteLine("Arrays are equal");
  } 
like image 192
slawekwin Avatar answered Oct 23 '25 19:10

slawekwin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!