NET 集合交集、並集、差集操作

Fish-Blog發表於2018-09-18
var list1 = new List<int> { 1, 3, 5, 7, 9, 11, 13, 15 };

var list2 = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
// List1:1 3 5 7 9 11 13 15
Console.WriteLine("List1:" + string.Join("	", list1));
// List2:1 2 3 4 5 6 7 8 9
Console.WriteLine("List2:" + string.Join("	", list2));

 

// 差集-List1有List2無:11 13 15
Console.WriteLine("差集-List1有List2無:" + string.Join("	", list1.Except(list2)));

 

// 交集-List1有List2有:1 3 5 7 9
Console.WriteLine("交集-List1有List2有:" + string.Join("	", list1.Intersect(list2)));

 

// 並集-包含List1和List2:1 3 5 7 9 11 13 15 2 4 6 8
Console.WriteLine("並集-包含List1和List2:" + string.Join("	", list1.Union(list2)));
Console.ReadLine();

 

相關文章