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 小时前
.NET 11 - 尝试一下Blazor中的新特性SupplyParameterFromTempData
microsoft·微软·c#·asp.net·.net·.netcore
1-1=019 小时前
C# 中 Lambda、Linq 与 Expression
c#·linq
zhanghaha131421 小时前
C# 系列教程_7 判断语句(分支)保姆级精讲
开发语言·c#
zhanghaha131421 小时前
C# 系列教程_8 循环语句 保姆级精讲(面向新手)
开发语言·c#
rockey6271 天前
AScript之LINQ扩展
c#·.net·script·动态脚本
张小姐的猫1 天前
【MySQL】访问 & 数据流动原理
android·数据库·mysql·adb·1024程序员节
1-1=01 天前
C# 委托与事件
开发语言·c#
1-1=02 天前
C# 特性(Attribute)
c#·.net·.netcore
工业HMI实战笔记2 天前
印刷电路板HMI:SMT贴装的元件定位界面
制造·设计规范·设计语言·1024程序员节
淡海水3 天前
10-01-互操作-C#与C++边界的内存管理
unity·c#·游戏引擎·.netcore·gc