您只需使用this overload of Distinct即可做到这一点。
以这个类为例:
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
}
您可以定义一个相等比较器,以便按名称比较 Student 的实例(也就是说,当且仅当 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;
}
}
然后您可以将自定义相等语义与 LINQ Distinct 扩展方法一起使用:
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();
}
}
上面的程序打印:
Enrico is 32
Alice is 18
正确实现接口 IEqualityComparer 的指南是可用的here