首頁 >後端開發 >C++ >如何使用 IEnumerable.Intersect() 找出多個清單的交集?

如何使用 IEnumerable.Intersect() 找出多個清單的交集?

Patricia Arquette
Patricia Arquette原創
2025-01-15 11:36:48753瀏覽

How to Find the Intersection of Multiple Lists Using IEnumerable.Intersect()?

使用 IEnumerable.Intersect() 找出多個清單的交集

C# 中的 IEnumerable.Intersect() 方法可讓您尋找兩個序列中的公共元素。但是,如果您有多個列表,並希望識別所有列表中都存在的元素,該怎麼辦?

問題:

給定一個整數列表列表:

<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>

如何使用 IEnumerable.Intersect() 找出這些清單的交集,得到結果 List() { 3 }?

解 1:HashSet 聚合

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

此解使用 Aggregate() 方法累積一個 HashSet,該 HashSet 表示清單的交集。 Skip(1) 方法確保 listOfLists 中的第一個清單用作 HashSet 的初始值。

解 2:HashSet 迭代

<code class="language-csharp">var intersection = new HashSet<int>(listOfLists.First());

foreach (var list in listOfLists.Skip(1))
{
    var intersect = new HashSet<int>(intersection);
    intersection.IntersectWith(list);
}</code>

此解也使用 HashSet,但它會迭代剩餘的列表,為每個交集建立一個新的 HashSet。

效能考量:

效能基準測試表明,在大多數情況下,HashSet 解決方案的效能優於使用 List。 foreach 方法和 Aggregate 方法在效能上差異可以忽略不計。

以上是如何使用 IEnumerable.Intersect() 找出多個清單的交集?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn