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();
相关推荐
小码编匠8 小时前
WPF 中的高级交互通过右键拖动实现图像灵活缩放
后端·c#·.net
唐青枫15 小时前
C#.NET 定时任务与队列利器:Hangfire 完整教程
c#·.net
hez201021 小时前
Runtime Async - 步入高性能异步时代
c#·.net·.net core·clr
mudtools1 天前
.NET驾驭Word之力:玩转文本与格式
c#·.net
唐青枫2 天前
C#.NET 数据库开发提速秘籍:SqlSugar 实战详解
c#·.net
mudtools2 天前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
大飞pkz3 天前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
唐青枫3 天前
从入门到进阶:C#.NET Stopwatch 计时与性能测量全攻略
c#·.net
未来之窗软件服务3 天前
幽冥大陆(二)RDIFSDK 接口文档:布草洗涤厂高效运营的技术桥梁C#—东方仙盟
开发语言·c#·rdif·仙盟创梦ide·东方仙盟
1uther3 天前
Unity核心概念⑨:Screen
开发语言·游戏·unity·c#·游戏引擎