无涯教程-LINQ - Union方法

75 阅读1分钟

在LINQ中,UNION方法或运算符用于将多个集合合并为单个集合,并返回具有唯一元素的结果集合。

下面是LINQ UNION方法的图形表示。

LINQ Union() Method

UNION方法将这两个集合合并为单个集合,并通过删除重复元素从集合中返回唯一元素。

LINQ联合方法的语法

下面是使用联合方法从多个集合中获取唯一元素的语法。

var result = count1.Union(count2);

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

LINQ UNION方法示例

下面是使用LINQ UNION方法的示例。

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", "USA", "UK", "Australia" }; string[] count2 = { "India", "Canada", "UK", "China" }; //count1.Union(count2) 用于从两个集合中找出唯一元素 var result = count1.Union(count2); //foreach 循环用于打印结果中包含的输出 foreach (var item in result) { Console.WriteLine(item); } Console.ReadLine(); } } }

在上面的示例中,我们使用 union 方法将两个集合“count1”,“count2”组合起来,以从两个集合中获取唯一元素。

输出:

LINQ Union() Method

参考链接

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