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 duplicat
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 in second
.
public static IEnumerable Overlap(this IEnumerable first,
IEnumerable second, IEqualityComparer comparer = null)
{
// argument checking, optimisations etc removed for brevity
var dict = new Dictionary(comparer);
foreach (T item in second)
{
int hits;
dict.TryGetValue(item, out hits);
dict[item] = hits + 1;
}
foreach (T item in first)
{
int hits;
dict.TryGetValue(item, out hits);
if (hits > 0)
{
yield return item;
dict[item] = hits - 1;
}
}
}