如何在保留重复项的同时进行整数列表交集?
我正在做最大公因数和最小公倍数作业,我必须列出公因数。 Intersection() 不起作用,因为它会删除重复项。 Contains() 不起作用,因为如果它在第二个列表中看到 int,它将返回第一个列表中的所有匹配 int。有没有办法做一个不独特的交叉点?
编辑:抱歉没有提供示例,这就是我的意思:
如果我有集合:
{1, 2, 2, 2, 3, 3, 4, 5}
{1, 1, 2, 2, 3, 3, 3, 4, 4}
我想要输出
{1, 2, 2, 3, 3, 4}
I'm working on a Greatest Common Factor and Least Common Multiple assignment and I have to list the common factors. Intersection() won't work because that removes duplicates. Contains() won't work because if it sees the int in the second list it returns all matching ints from the first list. Is there a way to do an Intersection that is not Distinct?
edit: sorry for not providing an example, here is what I meant:
if I have the sets:
{1, 2, 2, 2, 3, 3, 4, 5}
{1, 1, 2, 2, 3, 3, 3, 4, 4}
I would want the output
{1, 2, 2, 3, 3, 4}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我写了这个扩展来解决问题:
示例:
结果:
I wrote this extension to solve the problem:
example:
result:
where 表达式在技术上是可选的,我觉得它使意图更清晰。
如果你想要更简洁的代码:
The where expression is technically optional, I feel it makes the intent clearer.
If you want more terse code:
您可以使用我为另一个答案编写的通用扩展,它本质上是一个单一的 Linq 语句。请注意,它使用
Zip
来避免不必要的匹配组的完整枚举。这使得能够
根据需要维持源序列的顺序。
You could use this generic extension I wrote for another answer, it is essentially a single Linq statement. Note that it uses
Zip
to avoid the needless full enumeration of matched groups.this enables,
maintaining the order of the source sequence, as desired.
您在寻找这样的东西吗?它应该是O(n+m),其中n是
first
和m中的项目数em> 是秒
中的项目数。Are you looking for something like this? It should be pretty-much O(n+m), where n is the number of items in
first
and m is the number of items insecond
.这是一种方法。公平地说,它与 David B 的答案非常相似,只是它使用连接来进行关联。
Here's one way to do it. To be fair, it is very similar to David B's answer except that it uses a join to do the association.
见下文:
See below: