Home >Backend Development >C++ >How Can IEnumerable.Intersect() Efficiently Find the Intersection of Multiple Lists?

How Can IEnumerable.Intersect() Efficiently Find the Intersection of Multiple Lists?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-15 11:14:45637browse

How Can IEnumerable.Intersect() Efficiently Find the Intersection of Multiple Lists?

Efficiently find the intersection of multiple lists: IEnumerable.Intersect() method

In programming, determining the intersection of multiple lists is a common problem. This problem can be easily solved with the help of .NET's powerful IEnumerable.Intersect() method.

Assume the following scenario: We have a list of lists and we want to find elements that are present in all lists. For example, given three lists:

<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 };</code>

The expected intersection will be the list:

<code class="language-csharp">{ 3 }</code>

This intersection can be computed efficiently using IEnumerable.Intersect(). However, it is important to note that this method requires us to provide a IEnumerable<T> as input.

To satisfy this requirement, we can aggregate multiple IEnumerable<T> objects into a single list, as shown in the following solution:

<code class="language-csharp">var listOfLists = new List<List<int>>() { list1, list2, list3 };
var intersection = listOfLists
    .Skip(1)
    .Aggregate(
        new HashSet<int>(listOfLists.First()),
        (h, e) => { h.IntersectWith(e); return h; }
    );</code>

This code iterates over the lists in listOfLists (except the first list) and updates HashSet.IntersectWith() with the intersection of HashSet with the current list. This efficient process ultimately results in the desired intersection, stored in the intersection variable.

This solution effectively leverages HashSet, which is optimized for fast intersection operations. Additionally, the code is clean and concise, making it ideal for this task.

The above is the detailed content of How Can IEnumerable.Intersect() Efficiently Find the Intersection of Multiple Lists?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn