要使Intersect方法正确识别自定义类型,需要实现IEqualityComparer接口来对自定义类型进行比较。以下是一个示例代码:
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List
{
new Student { Id = 1, Name = "Alice" },
new Student { Id = 2, Name = "Bob" },
new Student { Id = 3, Name = "Charlie" }
};
List
{
new Student { Id = 2, Name = "Bob" },
new Student { Id = 4, Name = "David" },
new Student { Id = 5, Name = "Eve" }
};
var intersectedStudents = list1.Intersect(list2, new StudentComparer());
foreach (var student in intersectedStudents)
{
Console.WriteLine($"Id: {student.Id}, Name: {student.Name}");
}
}
class Student
{
public int Id { get; set; }
public string Name { get; set; }
}
class StudentComparer : IEqualityComparer
{
public bool Equals(Student x, Student y)
{
return x.Id == y.Id && x.Name == y.Name;
}
public int GetHashCode(Student obj)
{
return obj.Id.GetHashCode() ^ obj.Name.GetHashCode();
}
}
}
```
在这个示例中,定义了一个Student类,并实现了IEqualityComparer接口来比较两个Student对象。然后,在Main方法中,创建了两个Student对象的列表,并使用Intersect方法找到两个列表中共同存在的元素。