Home > Backend Development > C++ > How to Efficiently Find the Intersection of Multiple Lists in C#?

How to Efficiently Find the Intersection of Multiple Lists in C#?

Patricia Arquette
Release: 2025-01-15 11:49:47
Original
699 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template