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();
相关推荐
钢铁男儿3 小时前
C#接口实现详解:从理论到实践,掌握面向对象编程的核心技巧
java·前端·c#
神所夸赞的夏天4 小时前
c#获取Datatable中某列最大或最小的行数据方法
开发语言·c#
我是唐青枫5 小时前
C#.NET serilog 详解
开发语言·c#·.net
future14125 小时前
项目开发日记
前端·学习·c#·游戏开发
我是苏苏15 小时前
C#基础:Winform桌面开发中窗体之间的数据传递
开发语言·c#
水果里面有苹果21 小时前
20-C#构造函数--虚方法
java·前端·c#
[纳川]1 天前
把word中表格转成excle文件
开发语言·c#·word
lph19721 天前
快速分页wpf
c#
试行1 天前
C#System.Runtime.InteropServices.ExternalException (0x80004005): GDI+ 中发生一般性错误。
c#