在C#中使用Intersect方法對自定義對象列表進行交集操作,需要重寫自定義對象的Equals和GetHashCode方法,以確保比較兩個對象是否相等的準確性。
假設有一個自定義對象Person,包含屬性Id和Name,示例代碼如下:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
{
return false;
}
Person other = (Person)obj;
return Id == other.Id && Name == other.Name;
}
public override int GetHashCode()
{
return Id.GetHashCode() ^ Name.GetHashCode();
}
}
然后創建兩個Person對象列表,使用Intersect方法找到它們的交集:
List<Person> list1 = new List<Person>
{
new Person { Id = 1, Name = "Alice" },
new Person { Id = 2, Name = "Bob" },
new Person { Id = 3, Name = "Charlie" }
};
List<Person> list2 = new List<Person>
{
new Person { Id = 2, Name = "Bob" },
new Person { Id = 3, Name = "Charlie" },
new Person { Id = 4, Name = "David" }
};
var intersectList = list1.Intersect(list2).ToList();
foreach (var person in intersectList)
{
Console.WriteLine(person.Id + " " + person.Name);
}
以上代碼將輸出:
2 Bob
3 Charlie