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

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 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()); //去重
        }
    }

 

转载于:https://www.cnblogs.com/yechangzhong-826217795/p/11417244.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值