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

转自:https://blog.csdn.net/cjh16606260986/article/details/143204300

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();

 

posted @ 2024-11-22 14:44  Haoeaoi  阅读(0)  评论(0编辑  收藏  举报