C# 中的两个数组的交集


要获取两个数组的交集,请使用 Intersect 方法。它是 System.Linq 命名空间中的扩展方法。

该方法返回两个数组之间的公共元素。

首先设置两个数组 −

int[] arr1 = { 44, 76, 98, 34 };
int[] arr2 = { 24, 98, 44, 55, 47, 86 };

现在在两个数组上使用 Intersect −

Arr1.Intersect(arr2);

以下是完整代码 −

示例

 实时演示

using System;
using System.Linq;

class Program {
   static void Main() {
      int[] arr1 = { 44, 76, 98, 34 };
      int[] arr2 = { 24, 98, 44, 55, 47, 86 };
      var intersect = arr1.Intersect(arr2);
      foreach (int res in intersect) {
         Console.WriteLine(res);
      }
   }
}

输出

44
98

更新时间: 20-Jun-2020

5K+ 浏览次数

开启你的 职业

完成课程获得认证

开始学习
广告
© . All rights reserved.