C# program to find Intersection of two lists

CsharpProgrammingServer Side Programming

To find intersection of two lists in C#, use the Intersect() method.

The following is our list 1.

List<int> list1 = new List<int>();
list1.Add(2);
list1.Add(3);
list1.Add(5);
list1.Add(7);

The following is our list 2.

List<int> list2 = new List<int>();
list2.Add(5);
list2.Add(4);
list2.Add(6);
list2.Add(8);

The following is the code to find the intersection of two lists in C#.

Example

 Live Demo

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Demo {
   public class Program {
      public static void Main(String[] args) {
         List<int> list1 = new List<int>();
         list1.Add(2);
         list1.Add(3);
         list1.Add(5);
         list1.Add(7);
         Console.WriteLine(list1.Count);
         List<int> list2 = new List<int>();
         list2.Add(5);
         list2.Add(4);
         list2.Add(6);
         list2.Add(8);
         Console.WriteLine(list2.Count);
         List<int> common = list1.Intersect(list2).ToList();
         Console.WriteLine(common.Count);
      }
   }
}

Output

4
4
1
raja
Published on 19-Sep-2018 07:18:00
Advertisements