两个集合交集

Two collections intersection

我正在尝试将两个集合相交。我在下面的代码片段中列出了两个列表。

这是我的输出:

Intersection
1

为什么只找到一个值?这是预期的行为还是我做错了什么?

我希望我的输出是这样的:

Intersection
1
1
1
1

我的代码:

// Collection initialization
List<int> list1 = new List<int> { 1,1,1,1 }; 
List<int> list2 = new List<int> { 1,1,1,1,1,1,1,1,1,1,1 };

foreach (int q in list1)
    Console.WriteLine("list1: " + q);

Console.WriteLine("------------------");

foreach (int q in list2)
    Console.WriteLine("list2: " + q);

Console.WriteLine("------------------");
Console.WriteLine("Intersection");

IEnumerable<int> both = list1.Intersect(list2);

foreach (int a in both)
    Console.WriteLine(a);

Console.ReadLine();
Console.Clear();

LINQ让您的工作更轻松。像这样使用 Contains 方法:

List<int> resultList = list1.Where(c => list2.Contains(c)).ToList();

请不要忘记先将 LINQ 添加到您的 using 指令中:

using System.Linq;

正如您在 Enumerable.Intersect 的描述中所读:

The intersection of two sets A and B is defined as the set that contains all the elements of A that also appear in B, but no other elements.

set 中,您只有不同的对象。所以把四个 1 放在一个集合里和只把它放在 1 次里是一样的。 这就是为什么您只能获得一个条目。

与两个列表中的 return 个唯一匹配元素相交