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();
这篇关于如何在保留重复项的同时进行整数列表交集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在保留重复项的同时进行整数列表交集?
基础教程推荐
- rabbitmq 的 REST API 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 将 XML 转换为通用列表 2022-01-01