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 0;
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 = 1, Name = "1", Age = 1 });
stuA.Add(new Student { Id = 5, Name = "5", Age = 2 });
stuB.Add(new Student { Id = 1, Name = "1", Age = 1 });
stuB.Add(new Student { Id = 2, Name = "2", Age = 2 });
stuB.Add(new Student { Id = 3, Name = "3", Age = 3 });
stuB.Add(new Student { Id = 4, Name = "4", Age = 4 });
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()); //去重
}
}
C# 集合的交集 差集 并集 去重
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...