Often times there are requirements to ensure there are no
duplicate entries in a collection. If you are familiar with SQL you would
probably immediately think of the “distinct” keyword. LINQ also provides a
Distinct() method that uses an objects Equals() method to test equality.
IEnumerable<int> intArr = new[] { 1, 2, 2, 3 };
intArr = intArr.Distinct(); //Has size 3
This works great for value types, common reference types
(like string), and for classes where you have access to override the Equals()
method. But what are you supposed to do when this isn’t the case and, for
example, you have a collection of a class you are consuming from an external
dependency (like the CDM)? Once again, LINQ provides a helpful overload for the
Distinct() method that takes an instance of an IEqualityComparer<T>. The
IEqualityComparer<T> class mimics the behavior of overriding the
Equals()and GetHashCode() methods for a class, so you can write all of the
equality logic directly into it and pass it to the Distinct() method which will
use it instead of the class’s Equals.
myClasses = myClasses.Distinct(new MyClassComparer());
…
public class MyClassComparer : IEqualityComparer<MyClass>
{
public bool Equals(MyClass x, MyClass y)
{
return x.DriversLicence == y.DriversLicence && x.DriversName == y.DriversName;
}
public int GetHashCode(MyClass obj)
{
return obj.DriversLicence.GetHashCode() + obj.DriversName.GetHashCode();
}
}