c# - 两个集合交集

标签 c# 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();

最佳答案

正如您在 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/

相关文章:

c# - 在执行响应的 XML 序列化时修改默认命名空间前缀

c# - 如何将MemoryStream写入文本文件的末尾

c# - 尝试协商时出现 SignalR 404 错误

scala - 如何在scala中对相邻元素求和

java - Java 中的贝叶斯网络实现

c# - ActionResult<IEnumerable<T>> 必须返回一个 List<T>

java 如何改变排序的优先级

java - 为什么枚举在 java.utils 中被转换为 ArrayList 而不是 List?

python - 查找字典中的值变化和索引

javascript - 使用 JavaScript 查找圆形 Canvas 交点