問(wèn)題描述
我正在處理最大公因數(shù)和最小公因數(shù)分配,我必須列出公因數(shù).Intersection() 將不起作用,因?yàn)樗鼤?huì)刪除重復(fù)項(xiàng).Contains() 將不起作用,因?yàn)槿绻诘诙€(gè)列表中看到 int,它會(huì)從第一個(gè)列表中返回所有匹配的 int.有沒(méi)有辦法做一個(gè)不相干的交叉點(diǎn)?
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?
抱歉沒(méi)有提供示例,這就是我的意思:
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 表達(dá)式在技術(shù)上是可選的,我覺(jué)得它使意圖更清晰.
The where expression is technically optional, I feel it makes the intent clearer.
如果你想要更簡(jiǎn)潔的代碼:
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();
這篇關(guān)于如何在保留重復(fù)項(xiàng)的同時(shí)進(jìn)行整數(shù)列表交集?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!