首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在C#中跨多个列表查找公共项的最快方法

在C#中,跨多个列表查找公共项的最快方法是使用哈希集合(HashSet)。哈希集合提供了高效的查找和交集操作。以下是一个示例代码:

代码语言:csharp
复制
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> list1 = new List<int> { 1, 2, 3, 4, 5 };
        List<int> list2 = new List<int> { 4, 5, 6, 7, 8 };
        List<int> list3 = new List<int> { 7, 8, 9, 10, 11 };

        HashSet<int> hashSet1 = new HashSet<int>(list1);
        HashSet<int> hashSet2 = new HashSet<int>(list2);
        HashSet<int> hashSet3 = new HashSet<int>(list3);

        hashSet1.IntersectWith(hashSet2);
        hashSet1.IntersectWith(hashSet3);

        Console.WriteLine("公共项为:");
        foreach (int item in hashSet1)
        {
            Console.WriteLine(item);
        }
    }
}

在这个示例中,我们首先将列表转换为哈希集合,然后使用 IntersectWith 方法找到它们之间的公共项。最后,我们遍历哈希集合并输出公共项。

这种方法的时间复杂度为 O(n),其中 n 是列表中项目的数量。由于哈希集合是基于哈希表实现的,因此它提供了非常快速的查找操作。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的合辑

领券