相交的两个数组


若要获取两个数组的交集,请使用 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 年 6 月 20 日

5 千 + 查看

开启你的职业生涯

通过完成课程来获得认证

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