我们经常会遇到这种情况,有A、B两个数组,需要取出两个数组之间重复的元素(交集Intersect),或者将A数组中的B元素去除(差集Except),又或者合并两个数组并且不出现重复的元素(并集Union),所幸的是LINQ提供了一些方法,可以很直接的获取这些结果。
取两数组的交集:
var arrA = new[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; var arrB = new[] {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}; var arrIntersect = arrA.Intersect(arrB); foreach (var item in arrIntersect) { Response.Write(item + ","); }
输出结果为:
2,4,6,8,10,
取两数组的差集:
var arrA = new[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; var arrB = new[] {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}; var arrExceptB = arrA.Except(arrB); var arrExceptA = arrB.Except(arrA); foreach (var item in arrExceptB) { Response.Write(item + ","); } Response.Write("<br/>"); foreach (var item in arrExceptA) { Response.Write(item + ","); }
输出结果为:
1,3,5,7,9, 12,14,16,18,20,
取两数组的并集:
var arrA = new[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; var arrB = new[] {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}; var arrUnion = arrA.Union(arrB); foreach (var item in arrUnion) { Response.Write(item + ","); }
输出结果为:
1,2,3,4,5,6,7,8,9,10,12,14,16,18,20,