Home >Backend Development >C++ >How to Efficiently Find the Intersection of Multiple Lists in C# using IEnumerable.Intersect()?
Use IEnumerable.Intersect() to efficiently find the intersection of multiple lists in C#
In the field of data analysis and processing, finding the intersection of multiple lists is a very common task. While there are multiple ways to solve this problem, using the IEnumerable.Intersect() method provides an efficient solution. This article explores how to use this method to identify and retrieve the intersection of multiple lists.
In C#, when applied to multiple sequences, the IEnumerable.Intersect() method can be used to obtain elements common to all sequences. To see how to use this method to find the intersection of multiple lists, consider the following example:
<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 }; // 预期交集为 List<int>() { 3 };</code>
To find the intersection of these lists using IEnumerable.Intersect() we can utilize the following method:
<code class="language-csharp">var intersection = listOfLists .Skip(1) .Aggregate( new HashSet<int>(listOfLists.First()), (h, e) => { h.IntersectWith(e); return h; } );</code>
In this solution we:
This solution provides a concise and efficient way to find the intersection of multiple lists using IEnumerable.Intersect(). It leverages the optimization features of HashSet to handle duplicate elements and perform fast intersection operations.
It is important to note that listOfLists should always contain at least one list to initialize the intersection with. If the list is empty, an ArgumentNullException is thrown.
The above is the detailed content of How to Efficiently Find the Intersection of Multiple Lists in C# using IEnumerable.Intersect()?. For more information, please follow other related articles on the PHP Chinese website!