1.

How to intersect two lists in C#?

Answer»

Two lists can be intersected using the Enumerable.Intersect() method in C#. These methods provide the COMMON elements from both the lists as result. The namespace System.Linq is required for the Enumerable.Intersect() method.

A program that demonstrates the intersection of two lists is given as follows:

using System; using System.Collections.Generic; using System.Linq; class Demo {    public static VOID Main()    {        List&LT;int> list1 = new List<int>();        list1.Add(7);        list1.Add(1);        list1.Add(5);        list1.Add(9);        list1.Add(3);        List<int> list2 = new List<int>();        list2.Add(9);        list2.Add(6);        list2.Add(4);        list2.Add(1);        list2.Add(7);        var intersection = list1.Intersect(list2);        Console.WriteLine("The elements in the intersection of the two lists are:");        foreach (int i in intersection)        {            Console.WriteLine(i);        }    } }

The output of the above program is as follows:

The elements in the intersection of the two lists are: 7 1 9


Discussion

No Comment Found