要使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方法找到兩個列表中共同存在的元素。