C# 集合的交集 差集 并集 去重

时间:2024-01-13 12:45:56

C# 集合的交集 差集 并集 去重

两个对象list,直接比较是不行的,因为他们存的地址不一样

需要重写GetHashCode()与Equals(object obj)方法告诉电脑

class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
} class CompareStudent : IEqualityComparer<Student>
{
public bool Equals(Student x, Student y)
{
return x.Id == y.Id;
} public int GetHashCode(Student p)
{
if (p == null)
return ;
return p.Id.GetHashCode();
}
} class Program
{
static void Main(string[] args)
{
List<Student> stuA = new List<Student>();
List<Student> stuB = new List<Student>();
stuA.Add(new Student { Id = , Name = "", Age = });
stuA.Add(new Student { Id = , Name = "", Age = });
stuB.Add(new Student { Id = , Name = "", Age = });
stuB.Add(new Student { Id = , Name = "", Age = });
stuB.Add(new Student { Id = , Name = "", Age = });
stuB.Add(new Student { Id = , Name = "", Age = });
var result = stuA.Where(a => !stuB.Exists(b => b.Id == a.Id)); //在A中存在不再B中存在 即求差集
var resc = stuA.Except(stuB, new CompareStudent()); //差集
var resj = stuA.Intersect(stuB, new CompareStudent());// 交集
var resb = stuA.Union(stuB, new CompareStudent()); //并集
var resD = stuB.Distinct(new CompareStudent()); //去重
}
}