Use of "Distinct" method with a custom equality comparer in LINQ
When using the Distinct
method in LINQ, you can provide a custom equality comparer to determine uniqueness based on your specific criteria. This allows you to define your own logic for comparing elements and identifying duplicates.
To use the Distinct
method with a custom equality comparer, you need to create a class that implements the IEqualityComparer<T>
interface, where T
is the type of elements in the sequence. This interface defines two methods: Equals
and GetHashCode
, which are used for comparing elements and generating hash codes respectively.
Here's an example of using the Distinct
method with a custom equality comparer:
class Student
{
public string StdName { get; set; }
public int StdAge { get; set; }
}
class StudentEqualityComparer : IEqualityComparer<Student>
{
public bool Equals(Student x, Student y)
{
return x.StdName == y.StdName && x.StdAge == y.StdAge;
}
public int GetHashCode(Student obj)
{
return obj.StdName.GetHashCode() ^ obj.StdAge.GetHashCode();
}
}
List<Student> people = new List<Student>
{
new Student { StdName = "Alice", StdAge = 25 },
new Student { StdName = "Bob", StdAge = 30 },
new Student { StdName = "Alice", StdAge = 25 }
};
IEnumerable<Student> distinctPeople = people.Distinct(new StudentEqualityComparer());
In this example, the Student
class is defined with StdName
and StdAge
properties. A custom StudentEqualityComparer
class is created, implementing the IEqualityComparer<Student>
interface. The Equals method is overridden to compare two Student
objects based on their StdName
and StdAge
properties, and the GetHashCode
method is implemented to generate a hash code for each Student
object.
The Distinct
method is then used with the custom equality comparer 'new' StudentEqualityComparer()
to remove duplicates from the people
collection. The resulting distinctPeople
variable will contain the unique Student
objects based on the custom equality comparison logic.
By providing a custom equality comparer, you can define your own rules for determining uniqueness when using the Distinct
method in LINQ.