Home >Backend Development >C++ >How to Efficiently Find the Intersection of Multiple Lists in C#?
Determining the Common Elements Across Multiple C# Lists
Imagine you have a collection of lists and need to identify the elements present in all of them. For instance:
<code class="language-csharp">var list1 = new List<int>() { 1, 2, 3 }; var list2 = new List<int>() { 2, 3, 4 }; var list3 = new List<int>() { 3, 4, 5 }; var listOfLists = new List<List<int>>() { list1, list2, list3 };</code>
The desired outcome is a list containing only the elements common to all three lists: {3}
.
Leveraging IEnumerable.Intersect()
with a List Accumulator
One effective method involves using IEnumerable.Intersect()
iteratively with a list acting as an accumulator:
<code class="language-csharp">var intersection = listOfLists.Skip(1) .Aggregate( new List<int>(listOfLists.First()), (list, subList) => list.Intersect(subList).ToList() );</code>
This code starts with the first list and then iteratively intersects it with each subsequent list.
Employing IEnumerable.Intersect()
with a HashSet Accumulator
A more efficient approach utilizes a HashSet
as the accumulator, due to its optimized intersection capabilities:
<code class="language-csharp">var intersection = listOfLists.Skip(1) .Aggregate( new HashSet<int>(listOfLists.First()), (h, e) => { h.IntersectWith(e); return h; } );</code>
This version employs IntersectWith()
, a more performant operation for sets. Remember, listOfLists
must contain at least one list for this to function correctly.
Both techniques provide efficient ways to find the intersection of multiple lists using IEnumerable.Intersect()
. The HashSet
method is generally preferred for its performance advantages when dealing with larger datasets.
The above is the detailed content of How to Efficiently Find the Intersection of Multiple Lists in C#?. For more information, please follow other related articles on the PHP Chinese website!