在C#中查找多个列表中的常用项

我有两个通用列表:

List TestList1 = new List(); List TestList2 = new List(); TestList1.Add("1"); TestList1.Add("2"); TestList1.Add("3"); TestList2.Add("3"); TestList2.Add("4"); TestList2.Add("5"); 

在这些列表中查找常用项目的最快方法是什么?

假设您使用具有LINQ的.Net版本,则可以使用Intersect扩展方法:

 var CommonList = TestList1.Intersect(TestList2) 

如果您有对象列表并想要获取某些属性的公共对象,则使用;

 var commons = TestList1.Select(s1 => s1.SomeProperty).ToList().Intersect(TestList2.Select(s2 => s2.SomeProperty).ToList()).ToList(); 

注意: SomeProperty引用了您要实现的某些条件。

假设你有LINQ可用。 我不知道它是否是最快的,但干净的方式是这样的:

 var distinctStrings = TestList1.Union(TestList2).Distinct(); 

 var distinctStrings = TestList1.Union(TestList2); 

更新:永远不要介意我的回答,我刚刚了解了Intersect!

根据评论中的更新,联盟应用了一个独特的,现在我考虑它是有道理的。

对两个数组进行排序并从两者的顶部开始,并比较它们是否相等。


使用哈希更快:将第一个数组放在哈希中,然后比较第二个数组中的每个项目(如果它已经在哈希中)。

我不知道那些相交和联盟是否已实施。 如果你关心性能,试着找出他们的运行时间。 当然,如果您需要干净的代码,它们更适合。

使用Intersect方法:

 IEnumerable result = TestList1.Intersect(TestList2); 

您可以通过计算所有列表中所有项目的出现次数来实现此目的 – 那些出现次数等于列表数量的项目对所有列表都是通用的:

  static List FindCommon(IEnumerable> lists) { Dictionary map = new Dictionary(); int listCount = 0; // number of lists foreach (IEnumerable list in lists) { listCount++; foreach (T item in list) { // Item encountered, increment count int currCount; if (!map.TryGetValue(item, out currCount)) currCount = 0; currCount++; map[item] = currCount; } } List result= new List(); foreach (KeyValuePair kvp in map) { // Items whose occurrence count is equal to the number of lists are common to all the lists if (kvp.Value == listCount) result.Add(kvp.Key); } return result; } 

使用HashSet进行快速查找。 这是解决方案:

 using System; using System.Linq; using System.Collections.Generic; public class Program { public static void Main() { List list1 = new List {1, 2, 3, 4, 5, 6 }; List list2 = new List {1, 2, 3 }; List list3 = new List {1, 2 }; var lists = new IEnumerable[] {list1, list2, list3 }; var commons = GetCommonItems(lists); Console.WriteLine("Common integers:"); foreach (var c in commons) Console.WriteLine(c); } static IEnumerable GetCommonItems(IEnumerable[] lists) { HashSet hs = new HashSet(lists.First()); for (int i = 1; i < lists.Length; i++) hs.IntersectWith(lists[i]); return hs; } }