在C#中,跨多个列表查找公共项的最快方法是使用哈希集合(HashSet)。哈希集合提供了高效的查找和交集操作。以下是一个示例代码:
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 是列表中项目的数量。由于哈希集合是基于哈希表实现的,因此它提供了非常快速的查找操作。
领取专属 10元无门槛券
手把手带您无忧上云