C# - Example of LINQ Union() Method

Learn about the Linq Union() method and its C# implementation with an example. By Nidhi Last updated : April 01, 2023

Here we will perform union operation between two lists using Linq Union() method and print the result on the console screen.

C# program to demonstrate the example of LINQ Union() method

The source code to demonstrate the Linq Union() method, is given below. The given program is compiled and executed successfully on 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 + " ");
        } 
    }
}

Output

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

Explanation

In the above program, we created two lists of integer numbers that are given below.

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

Here we used Linq Union() method to perform union operation between two lists using the below code.

var result = List1.Union(List2);

Then we print the result on the console screen using the below code using the "foreach" loop.

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

C# LINQ Programs »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.