CSharp - EqualityComparer<T> Implement

Introduction

You can implement EqualityComparer to control the equality behaviour for your own object.

The following code creates a Person class with two fields, and then create an equality comparer that matches both the first and last names:

class Person
{
       public string LastName;
       public string FirstName;

       public Person (string last, string first)
       {
         LastName = last;
         FirstName = first;
       }
}
class LastFirstEqComparer : EqualityComparer <Person>
{
       public override bool Equals (Person x, Person y)
         => x.LastName == y.LastName && x.FirstName == y.FirstName;

       public override int GetHashCode (Person obj)
         => (obj.LastName + ";" + obj.FirstName).GetHashCode();
}

To illustrate how this works, we'll create two customers:

Person c1 = new Person ("A", "B");
Person c2 = new Person ("A", "B");

Because we've not overridden object.Equals, normal reference type equality semantics apply:

Console.WriteLine (c1 == c2);               // False
Console.WriteLine (c1.Equals (c2));         // False

The same default equality semantics apply when using these customers in a Dictionary without specifying an equality comparer:

var d = new Dictionary<Person, string>();
d [c1] = "B";
Console.WriteLine (d.ContainsKey (c2));         // False

The following code uses the customized Comparer:

var eqComparer = new LastFirstEqComparer();
var d = new Dictionary<Person, string> (eqComparer);
d [c1] = "B";
Console.WriteLine (d.ContainsKey (c2));         // True

Demo

using System;
using System.Collections.Generic;

class Person/*from  w ww  .ja  va2  s .  c  om*/
{
    public string LastName;
    public string FirstName;

    public Person(string last, string first)
    {
        LastName = last;
        FirstName = first;
    }
}
class LastFirstEqComparer : EqualityComparer<Person>
{
    public override bool Equals(Person x, Person y)
      => x.LastName == y.LastName && x.FirstName == y.FirstName;

    public override int GetHashCode(Person obj)
      => (obj.LastName + ";" + obj.FirstName).GetHashCode();
}

class MainClass
{
    public static void Main(string[] args)
    {
        Person c1 = new Person("A", "B");
        Person c2 = new Person("A", "B");
        Console.WriteLine(c1 == c2);               // False
        Console.WriteLine(c1.Equals(c2));         // False
        var d = new Dictionary<Person, string>();
        d[c1] = "B";
        Console.WriteLine(d.ContainsKey(c2));         // False
        var eqComparer = new LastFirstEqComparer();
        d = new Dictionary<Person, string>(eqComparer);
        d[c1] = "B";
        Console.WriteLine(d.ContainsKey(c2));         // True

    }
}

Result