Intersect two lists in C#


Firstly, set two lists.

List<int> val1 = new List<int> { 25, 30, 40, 60, 80, 95, 110 };
List<int> val2 = new List<int> { 27, 35, 40, 75, 95, 100, 110 };

Now, use the Intersect() method to get the intersection between two lists.

IEnumerable<int> res = val1.AsQueryable().Intersect(val2);

Example

 Live Demo

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

class Demo {
   static void Main() {
      List<int> val1 = new List<int> { 25, 30, 40, 60, 80, 95, 110 };
      List<int> val2 = new List<int> { 27, 35, 40, 75, 95, 100, 110 };
      IEnumerable<int> res = val1.AsQueryable().Intersect(val2);
      Console.WriteLine("Intersection of both the lists...");
      foreach (int a in res) {
         Console.WriteLine(a);
      }
   }
}

Output

Intersection of both the lists...
40
95
110

Updated on: 22-Jun-2020

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements