怎么使用LINQ Intersect方法比较两个字符串数组

1354
2024/4/7 9:58:25
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

你可以使用LINQ Intersect方法来比较两个字符串数组,找出它们共同的元素。下面是一个示例:

```csharp

using System;

using System.Linq;

class Program

{

static void Main()

{

string[] array1 = { "apple", "banana", "orange", "grape" };

string[] array2 = { "orange", "grape", "kiwi", "pear" };

var commonElements = array1.Intersect(array2);

Console.WriteLine("Common elements in the two arrays:");

foreach (var element in commonElements)

{

Console.WriteLine(element);

}

}

}

```

在上面的示例中,我们定义了两个字符串数组`array1`和`array2`,然后使用LINQ的`Intersect`方法找出这两个数组的共同元素。最后,我们遍历输出共同元素的值。运行该程序,输出将会是:

```

Common elements in the two arrays:

orange

grape

```

这表明`array1`和`array2`中共同的元素是"orange"和"grape"。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: linq中groupby的用法是什么