How do I do an integer list intersection while keeping duplicates?(如何在保留重复项的同时进行整数列表交集?)
问题描述
我正在处理最大公因数和最小公因数分配,我必须列出公因数.Intersection() 将不起作用,因为它会删除重复项.Contains() 将不起作用,因为如果它在第二个列表中看到 int,它会从第一个列表中返回所有匹配的 int.有没有办法做一个不相干的交叉点?
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:
如果我有套装:
{1, 2, 2, 2, 3, 3, 4, 5}
{1, 1, 2, 2, 3, 3, 3, 4, 4}
我想要输出
{1, 2, 2, 3, 3, 4}
推荐答案
ILookup<int, int> lookup1 = list1.ToLookup(i => i);
ILookup<int, int> lookup2 = list2.ToLookup(i => i);
int[] result =
(
from group1 in lookup1
let group2 = lookup2[group1.Key]
where group2.Any()
let smallerGroup = group1.Count() < group2.Count() ? group1 : group2
from i in smallerGroup
select i
).ToArray();
where 表达式在技术上是可选的,我觉得它使意图更清晰.
The where expression is technically optional, I feel it makes the intent clearer.
如果你想要更简洁的代码:
If you want more terse code:
ILookup<int, int> lookup2 = list2.ToLookup(i => i);
int[] result =
(
from group1 in list1.GroupBy(i => i)
let group2 = lookup2[group1.Key]
from i in (group1.Count() < group2.Count() ? group1 : group2)
select i
).ToArray();
这篇关于如何在保留重复项的同时进行整数列表交集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在保留重复项的同时进行整数列表交集?


- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- C# 中多线程网络服务器的模式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01