You can do that simply by using this overload of Distinct.
Consider this class as an example:
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
}
You can define an equality comparer so that instances of Student
are compared by name (that is, two instances of Student
are considered equal if and only if they have the same value for Name
):
public class StudentComparerByName : IEqualityComparer<Student>
{
public bool Equals(Student x, Student y)
{
if (x == null && y == null)
{
return true;
}
if (x == null || y == null)
{
return false;
}
return string.Equals(x.Name, y.Name);
}
public int GetHashCode(Student obj)
{
if (obj == null)
throw new ArgumentNullException(nameof(obj));
return obj.Name?.GetHashCode() ?? 0;
}
}
Then you can use your custom equality semantic along with the LINQ Distinct
extension method:
public static class Program
{
public static void Main(string[] args)
{
var students = new[]
{
new Student { Name = "Enrico", Age = 32 },
new Student { Name = "Alice", Age = 18 },
new Student { Name = "Enrico", Age = 40 }
};
foreach (var student in students.Distinct(new StudentComparerByName()))
{
Console.WriteLine($"{student.Name} is {student.Age}");
}
Console.ReadLine();
}
}
The above program prints:
Enrico is 32
Alice is 18
The guidelines to properly implement the interface IEqualityComparer are available here