Union Method in C#


The Union method gets the unique elements from both the lists.

Let us set two lists −

var list1 = new List<int>{12, 65, 88, 45};
var list2 = new List<int>{40, 34, 65};

Now get the union of both the lists −

var res = list1.Union(list2);

The following is the example −

Example

 Live Demo

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

public class Demo {
   public static void Main() {

      // two lists
      var list1 = new List<int>{12, 65, 88, 45};
      var list2 = new List<int>{40, 34, 65};

      // finding union
      var res = list1.Union(list2);

      foreach(int i in res) {
         Console.WriteLine(i);
      }
   }
}

Output

12
65
88
45
40
34

Updated on: 22-Jun-2020

484 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements