Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

1 Answer
Samual Sam

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

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.