C# 两个List 比较(交集、差集、并集)

在开发中对比两个集合的操作也是常有的。最近我又用上了。在这里分享一下。

交集、差集、并集

复制代码
List<int> list1 = new List<int>() { 1, 3, 5, 7, 9 };
List<int> list2 = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

//求差集 求不同
var exceptList = list2.Except(list1).ToList();
Console.WriteLine("求差集:" + string.Join(",", exceptList));

//求交集 求相同
var intersectList = list2.Intersect(list1).ToList();
Console.WriteLine("求交集:" + string.Join(",", intersectList));

//求并集 将两个集合的数据合并到一起
var unionList = list2.Union(list1).ToList();
Console.WriteLine("求并集:" + string.Join(",", unionList));

Console.ReadLine();
相关推荐
暴走约伯19 小时前
【VFX工具链源码拆解 09】终极工业化闭环:基于 ID 规则驱动的全自动场景建档、骨骼挂载与男转女场景迁移
unity·c#·游戏引擎·材质
用户788477316342 天前
WinForms 迁移 WPF:Upgrade Assistant 覆盖 30%,剩下 70% 我手写了六周
c#
寂寞的船2 天前
【Unity知识速递】第13期 Unity 内存泄漏排查实战:从 Memory Profiler 到 Lua 引用泄漏的生产级全链路诊断
unity·junit·c#·游戏引擎·lua
普通人62 天前
WebGL与WebGPU入门指南
开发语言·webgl·1024程序员节
用户3721574261353 天前
C# 提取 PDF 附件:包括文档附件和页面注释附件
c#
寂寞的船3 天前
【Unity Bug挑战】第12期 Awaitable 二次 await 死锁之谜 —— 为什么同一个异步操作等两次就卡死?
unity·c#·游戏引擎·bug
猫猫不是喵喵.3 天前
从0到1创建一个微服务项目
java·数据库·微服务·1024程序员节
huaqianzkh4 天前
WinForm C#:循环修改控件UI闪烁卡顿?SuspendLayout / ResumeLayout 与 BeginUpdate 优化
开发语言·ui·c#
用户3721574261355 天前
C# 实现 Excel 单元格保护:锁定公式并允许编辑指定区域
c#·ai编程·编程语言
公子小六5 天前
基于.NET的Windows窗体编程之WinForms数据持久化(1)
windows·microsoft·c#·.net·winforms