How to check whether two lists items have value equality using EqualityComparer?
10:50 11 Sep 2017

I have an Account class:

class Account
{
    List Contacts;

    // other properties, constructor, etc.
}

Using Visual Studio Community 2017, when opening the quick actions menu for this class, I can choose "Generate Equals(object)".

Here is the generated Equals:

public override bool Equals(object obj)
{
    var account = obj as Account;
    return account != null &&
           EqualityComparer>.Default.Equals(Contacts, account.Contacts) &&
            // checking equality for other properties
}

When I try to pass an account with the same list of contacts (same values), the method returns false.

Digging a little bit, I found that the problem is in this line:

EqualityComparer>.Default.Equals(Contacts, account.Contacts)

So if for example, I pass the following lists, the above expression will be false.

var a = new List(new Contact("Michael"), new Contact("John")); 
var b = new List(new Contact("Michael"), new Contact("John"));

And that is understandable since the two lists have different references. How could I change it so it will check for value equality inside the list?

Note: Contact overrides Equals to check for value equality, so checking equality for two different instances of new Contact("Michael") returns true.


Edit: If I was not clear, I want the items of the lists to have value equality regardless of their order.

c# list equality