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

How Can IEnumerable.Intersect() Find the Intersection of Multiple Lists in C#?

Barbara Streisand
Release: 2025-01-15 12:13:44
Original
659 people have browsed it

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

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

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!

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