无涯教程-LINQ - Intersect方法

67 阅读1分钟

在LINQ中,INTERSECT方法或运算符用于返回两个集合中的公共元素。

下面是LINQ交集方法的图示。

LINQ Intersect Method

LINQ INTERSECT方法将把这两个集合合并到单个集合中,并且只返回该集合中匹配的元素。

LINQ INTERSECT方法的语法

使用INTERSECT方法从多个集合中获取匹配元素的语法。

var result = count1.Intersect(count2);

根据上面的语法,无涯教程使用INTERSECT方法将两个集合组合在一起,以获得作为单个集合的结果。

LINQ交集方法示例

下面是LINQ INTERSECT方法的示例。

using System;
using System. Collections;
using System.Collections.Generic;
using System. Linq;
using System. Text;
using System.Threading.Tasks;

namespace ConsoleApp1 { class Programme2 { static void Main(string[] args) { //声明字符串类型的两个数组变量count1和count2 string[] count1 = { "India", "Australia", "UK", "USA" }; string[] count2 = { "India", "China", "UK", "China" }; /在两个数组上应用 Intersect 方法 count1 和 count2 并将输出存储在结果变量中/ var result = count1.Intersect(count2); /foreach 循环将遍历所有元素存储结果变量输出的变量项/ foreach (var item in result) { /Console.WriteLine(item) 打印 所有元素都存储在 item 变量中。/ Console.WriteLine(item); } Console.ReadLine(); } } }

输出:

LINQ Intersect Method

参考链接

www.learnfk.com/linq/linq-i…