如何在保留重复项的同时进行整数列表交集? [英] How do I do an integer list intersection while keeping duplicates?

查看:11
本文介绍了如何在保留重复项的同时进行整数列表交集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理最大公因数和最小公因数分配,我必须列出公因数.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();

这篇关于如何在保留重复项的同时进行整数列表交集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆