阅读量:0
在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