1.

What is the role of Union() Method in C#?

Answer»

The Union() method PERFORMS the union of two collections. The resultant collection contains all the elements from both the collections but there are no duplicates. Also, The namespace System.Linq is required for the Union() method.

A program that demonstrates the union of two lists using the Union() method is given as follows:

using System; using System.Collections.Generic; using System.Linq; class DEMO {    PUBLIC static void Main()    {        List<int> list1 = new List<int>();        list1.Add(4);        list1.Add(1);        list1.Add(8);        list1.Add(2);        list1.Add(3);        List<int> LIST2 = new List<int>();        list2.Add(9);        list2.Add(1);        list2.Add(3);        list2.Add(7);        list2.Add(2);        var union = list1.Union(list2);        Console.WriteLine("The elements in the union of the two lists are:");        foreach (int i in union)        {            Console.WriteLine(i);        }    } }

The OUTPUT of the above program is as follows:

The elements in the union of the two lists are: 4 1 8 2 3 9 7


Discussion

No Comment Found