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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM