检查两个List <int>的相同数字

Ger*_*nck 21 .net c# generics list

我有两个List,我想检查相应的数字.

例如

List<int> a = new List<int>(){1, 2, 3, 4, 5};
List<int> b = new List<int>() {0, 4, 8, 12};
Run Code Online (Sandbox Code Playgroud)

应该给出结果4.有没有一个简单的方法来做到这一点,而没有太多循环列表?

我在3.0的项目中需要这个,所以没有Linq.

ljs*_*ljs 30

您可以使用.net 3.5 .Intersect()扩展方法: -

List<int> a = new List<int>() { 1, 2, 3, 4, 5 };
List<int> b = new List<int>() { 0, 4, 8, 12 };

List<int> common = a.Intersect(b).ToList();
Run Code Online (Sandbox Code Playgroud)


kir*_*kus 11

Jeff Richter出色的PowerCollections设置了交叉点.一直工作回.NET 2.0.

http://www.codeplex.com/PowerCollections

        Set<int> set1 = new Set<int>(new[]{1,2,3,4,5});
    Set<int> set2 = new Set<int>(new[]{0,4,8,12});
    Set<int> set3 = set1.Intersection(set2);
Run Code Online (Sandbox Code Playgroud)


Jon*_*eet 9

你可以像LINQ那样有效地做到这一点 - 用一套.现在在3.5之前我们没有一个合适的集合类型,所以你需要使用Dictionary<int,int>或类似的东西:

  • 使用元素作为条目的键和值,Dictionary<int, int>从列表创建并填充它a.(条目中的值确实无关紧要.)
  • 为交叉点创建一个新列表(或者将其写为迭代器块,无论如何).
  • 迭代列表b,并使用dictionary.ContainsKey检查:如果是,请在列表中添加一个条目或者将其生成.

那应该是O(N + M)(即两个列表大小都是线性的)

请注意,如果列表b包含重复项,则会为您提供重复的条目.如果您想避免这种情况,当您第一次在列表中看到它时,您总是可以更改字典条目的值b.