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

xiaoxiao2021-02-28  34

1. 交集

(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

2. 差集

(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

3. 并集

(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 }

转载请注明原文地址: https://www.6miu.com/read-1650101.html

最新回复(0)