Search code examples
c#generics

find common items across multiple lists in C#


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?


Solution

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

    var CommonList = TestList1.Intersect(TestList2)