C# 对List<T>取交集、连集及差集

實際演練


※本文使用int為例,若為使用自訂之DataModel,需實作IEquatable<T>介面才能使用

1.  取交集 (A和B都有)

List A : { 1 , 2 , 3 , 5 , 9 }

List B : { 4 , 3 , 9 }

var intersectedList = list1.Intersect(list2);

結果 : { 3 , 9 }

判断A和B是否有交集

 bool isIntersected = list1.Intersect(list2).Count() > 0

2. 取差集 (A有,B沒有)

List A : { 1 , 2 , 3 , 5 , 9 }

List B : { 4 , 3 , 9 }

var expectedList = list1.Except(list2);

結果 : { 1 , 2 , 5 }

判断A和B是否有差集

bool isExpected = list1.Expect(list2).Count() > 0

 

3.  取并集 (包含A和B)

List A : { 1 , 2 , 3 , 5 , 9 }

List B : { 4 , 3 , 9 }

var mergedList = list1.Union(list2);
 

結果 : { 1 , 2 , 3 , 5 ,9 , 4 }

原文地址:https://www.cnblogs.com/xiaoxiaomini/p/8276991.html