C#: LINQ – Equality Comparer

Please see my other LINQ articles.

Implement an Equality Comparer to customize Contains().

In this article I’ll demonstrate how to override Contains() when searching a collection to specify which properties of objects to search.

First, I’ll get a collection of static People objects.

Now, I’ll implement a custom Equality Comparer class where I’ll override Equals() to search each object’s FirstName instead of just search object references.

Notice, I must also override GetHasCode().

Now I’ll instantiate my new PersonComparer class and a Person object to find in my collection.

When I pass both into Contains(), my customized version is used instead.