Home >Backend Development >C++ >How Can IEnumerable.Intersect() Find the Intersection of Multiple Lists in C#?
Use IEnumerable.Intersect() to find the intersection of multiple lists in C#
In C#, you can use IEnumerable.Intersect()
to find common elements of multiple lists efficiently.
Problem Description
Suppose you have a set of lists and need to find their intersection element. For 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>
The task is to use IEnumerable.Intersect()
to implement this intersection search.
Solution
To perform the intersection operation on multiple lists, use IEnumerable.Intersect()
iteratively. Using a foreach
loop, first calculate the intersection of the first two lists, then intersect the result with the third list, and so on until all lists have been processed.
<code class="language-csharp">// 使用第一个列表初始化交集 var intersection = listOfLists[0].ToHashSet(); // 与其余列表求交集 foreach (var list in listOfLists.Skip(1)) { intersection.IntersectWith(list.ToHashSet()); }</code>
This solution is simple and easy.
Performance Notes
Performance of this solution may vary depending on the number and size of lists. For large data sets, it is recommended to use a more optimized solution, such as using HashSet
.
The above is the detailed content of How Can IEnumerable.Intersect() Find the Intersection of Multiple Lists in C#?. For more information, please follow other related articles on the PHP Chinese website!