(1)取交集 (A和B都有) List A : { 1 , 2 , 3 , 5 , 9 } List B : { 4 , 3 , 9 }
var intersectedList = list1.Intersect(list2);结果 : { 3 , 9 }
(2)判斷A和B是否有交集
bool isIntersected = list1.Intersect(list2).Count() > 0(1)取差集 (A有,B沒有) List A : { 1 , 2 , 3 , 5 , 9 } List B : { 4 , 3 , 9 }
var expectedList = list1.Except(list2);结果 : { 1 , 2 , 5 }
(2)判断A和B是否有差集
bool isExpected = list1.Expect(list2).Count() > 0(1)取并集(包含A和B) List A : { 1 , 2 , 3 , 5 , 9 } List B : { 4 , 3 , 9 }
public static class ListExtensions { public static List<T> Merge<T>(this List<T> source, List<T> target) { List<T> mergedList = new List<T>(source); mergedList.AddRange(target.Except(source)); return mergedList; } } var mergedList = list1.Merge(list2);结果 : { 1 , 2 , 3 , 5 ,9 , 4 }