在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
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: C# MVVM模式中的命令传递机制