List之Union(),Intersect(),Except() 即并集,交集,差集运算。
2016-12-29 00:00
459 查看
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sample2 { class Program { static void Main(string[] args) { //List之Union(),Intersect(),Except() 即并集,交集,差集运算 IList<Student> Students1 = new List<Student>(); Students1.Add(new Student(1, false, "张三", "深圳")); Students1.Add(new Student(2, false, "李四", "广州")); Students1.Add(new Student(3, false, "王五", "珠海")); Students1.Add(new Student(4, false, "赵六", "东莞")); IList<Student> Students2 = new List<Student>(); Students2.Add(new Student(1, false, "张三", "深圳")); Students2.Add(new Student(5, false, "李七", "广州")); Students2.Add(new Student(6, false, "孙八", "深圳")); Students2.Add(new Student(7, true, "赵燕", "深圳")); //自定义比较规则 var bingji = Students1.Union(Students2, new StudentListEquality()).ToList();//并集(AB集合所有项) var jiaoji = Students1.Intersect(Students2, new StudentListEquality()).ToList();//交集 (AB集合共同项) var chaji = Students1.Except(Students2, new StudentListEquality()).ToList();//差集(A集合有,B没有) Console.WriteLine("以下是并集的结果"); bingji.ForEach(x => { Console.WriteLine(x.Id.ToString() + " " + x.Sex.ToString() + " " + x.Name.ToString() + " " + x.Address.ToString()); }); Console.WriteLine("以下是交集的结果"); jiaoji.ForEach(x => { Console.WriteLine(x.Id.ToString() + " " + x.Sex.ToString() + " " + x.Name.ToString() + " " + x.Address.ToString()); }); Console.WriteLine("以下是差集的结果"); chaji.ForEach(x => { Console.WriteLine(x.Id.ToString() + " " + x.Sex.ToString() + " " + x.Name.ToString() + " " + x.Address.ToString()); }); Console.ReadKey(); } } public class Student { public Student(int id, bool sex, String name, String address) { this.Id = id; this.Sex = sex; this.Name = name; this.Address = address; } public int Id { get; set; } public bool Sex { get; set; } public String Name { get; set; } public String Address { get; set; } } public class StudentListEquality : IEqualityComparer<Student> { public bool Equals(Student x, Student y) { return x.Id == y.Id && x.Name == y.Name && x.Address == y.Address && x.Sex == y.Sex; } public int GetHashCode(Student obj) { return (obj == null) ? 0 : obj.ToString().GetHashCode(); } } }
相关文章推荐
- 在C#中进行数据纵向不定行转横向列,多条信息成一行,例如员工薪资信息
- 话说linux内核
- asp.net中Execl文件的导入导出
- c# Linq操作XML,查找节点数据
- ListBox实现上移,下移,左移,右移操作
- Jquery几行代码解决跟随屏幕滚动DIV
- powerdesigner中sql脚本小写转大写,去双引号
- Jquery购物车jsorder改进版,支持后台处理程序直接转换成DataTable处理
- asp.net mvc5中使用缓存依赖SqlCacheDependency
- C# 将数据导出到Execl汇总
- SqlServer和Oracle中一些常用的sql语句8 触发器和事务
- CodeSmith(C#)简单示例及相关小知识
- Repeater嵌套绑定Repeater
- C#获取cpu序列号 硬盘ID 网卡硬地址以及操作注册表
- 配置java环境变量
- MSSQL 自定义函数详解
- MySQL存储过程例子,包含事务,参数,嵌套调用,游标,循环等
- DataTable 行列转换 将原来的行表转化成交叉表,无对应值赋默认值,用于统计显示或报表
- 弱校软件构件与中间件技术试题(2016)
- C#打印机操作类