我正在尝试将两个集合相交。我在下面的代码片段中列出了两个列表。
这是我的输出:
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();
最佳答案
正如您在 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 次里是一样的。 这就是为什么您只能获得一个条目。
关于c# - 两个集合交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47235615/