博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C# 集合的交集 差集 并集 去重
阅读量:4553 次
发布时间:2019-06-08

本文共 1620 字,大约阅读时间需要 5 分钟。

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
{ 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
stuA = new List
(); List
stuB = new List
(); 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

你可能感兴趣的文章
aws cli command line interface的安装与使用
查看>>
10)将地址换成常量
查看>>
cocos2d-x3.0 解释具体的新的物理引擎setCategoryBitmask()、setContactTestBitmask()、setCollisionBitmask()...
查看>>
Cocos2d-x
查看>>
FIR滤波器设计
查看>>
1005 继续(3n+1)猜想 (25 分)
查看>>
【Uva 1252】Twenty Questions
查看>>
1_访问命令行
查看>>
File操作相关
查看>>
Linux:文本处理工具
查看>>
java,for穷举,经典题目,百鸡百钱
查看>>
mysql提示Column count doesn't match value count at row 1错误
查看>>
前端--jstree--异步加载数据
查看>>
CSS定位深入理解 完全掌握CSS定位 相对定位和绝对定位
查看>>
网络体系结构
查看>>
练习4.13、4.14、4.15、4.16
查看>>
SAP库龄表
查看>>
PhantomJS 基础及示例 (转)
查看>>
20175316盛茂淞 2018-2019-2 《Java程序设计》第3周学习总结
查看>>
zookeeper安装
查看>>