當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C# Linq Union()用法及代碼示例

這裏我們將使用 Linq Union() 方法在兩個列表之間執行聯合操作,並在控製台屏幕上打印結果。

程序:

下麵給出了演示 Linq Union() 方法的源代碼。給定的程序在 Microsoft Visual Studio 上編譯並成功執行。

//C# Program to demonstrate Linq Union() method.

using System;
using System.Linq;
using System.Collections.Generic;

class Demo
{
    static void Main(string[] args)
    {
        List<int> List1 = new List<int>() { 10, 20, 30, 40, 50 };
        List<int> List2 = new List<int>() { 10, 40, 60, 80, 90 };

        var result = List1.Union(List2);

        foreach (var value in result)
        {
            Console.WriteLine(value + " ");
        } 
    }
}

輸出:

10
20
30
40
50
60
80
90
Press any key to continue . . .

說明:

在上麵的程序中,我們創建了下麵給出的兩個整數列表。

List<int> List1 = new List<int>() { 10, 20, 30, 40, 50 };
List<int> List2 = new List<int>() { 10, 40, 60, 80, 90 };

這裏我們使用 Linq Union() 方法使用以下代碼在兩個列表之間執行聯合操作。

var result = List1.Union(List2);

然後我們使用以下代碼使用 "foreach" 循環在控製台屏幕上打印結果。

foreach (var value in result)
{
    Console.WriteLine(value + " ");
} 



相關用法


注:本文由純淨天空篩選整理自 C# program to demonstrate the example of Linq Union() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。