Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find common items across multiple lists in C#

Tags:

c#

generics

I have two generic list :

List<string> TestList1 = new List<string>(); List<string> TestList2 = new List<string>(); TestList1.Add("1"); TestList1.Add("2"); TestList1.Add("3"); TestList2.Add("3"); TestList2.Add("4"); TestList2.Add("5"); 

What is the fastest way to find common items across these lists?

like image 994
Shahin Avatar asked Jun 29 '11 11:06

Shahin


2 Answers

Assuming you use a version of .Net that has LINQ, you can use the Intersect extension method:

var CommonList = TestList1.Intersect(TestList2) 
like image 56
Maximilian Mayerl Avatar answered Sep 23 '22 15:09

Maximilian Mayerl


If you have lists of objects and want to get the common objects for some property then use;

var commons = TestList1.Select(s1 => s1.SomeProperty).ToList().Intersect(TestList2.Select(s2 => s2.SomeProperty).ToList()).ToList(); 

Note: SomeProperty refers to some criteria you want to implement.

like image 44
Baqer Naqvi Avatar answered Sep 24 '22 15:09

Baqer Naqvi