Find common items across multiple lists in C#
This post will discuss how to find common items across multiple lists in C#.
1. Using Enumerable.Intersect() Method
The standard solution to find the set intersection of two sequences is using the Enumerable.Intersect method. It uses the default equality comparer or the specified IEqualityComparer<T> to compare values. It is available in LINQ and can be used as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { var first = new List<int> { 1, 2, 3, 4, 5 }; var second = new List<int> { 2, 4, 6, 8 }; var common = first.Intersect(second); Console.WriteLine(String.Join(", ", common)); // 2, 4 } } |
2. Using List<T>.FindAll() Method
The List<T>.FindAll() method retrieves all the elements that match the conditions defined by the specified predicate. It can be used as follows to find the common items across two lists.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { var first = new List<int> { 1, 2, 3, 4, 5 }; var second = new List<int> { 2, 4, 6, 8 }; var common = first.FindAll(x => second.Contains(x)); Console.WriteLine(String.Join(", ", common)); // 2, 4 } } |
That’s all about finding common items across multiple lists in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)