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
You could use this generic extension I wrote for another answer, it is essentially a single Linq statement. Note that it uses Zip
to avoid the needless full enumeration of matched groups.
public static IEnumerable Commom(
this IEnumerable source,
IEnumerable sequence,
IEqualityComparer comparer = null)
{
if (sequence == null)
{
return Enumerable.Empty();
}
if (comparer == null)
{
comparer = EqualityComparer.Default;
}
return source.GroupBy(t => t, comparer)
.Join(
sequence.GroupBy(t => t, comparer),
g => g.Key,
g => g.Key,
(lg, rg) => lg.Zip(rg, (l, r) => l),
comparer)
.SelectMany(g => g);
}
this enables,
new[] {1, 2, 2, 2, 3, 3, 4, 5}.Common(
new[] {1, 1, 2, 2, 3, 3, 3, 4, 4}).ToArray()
maintaining the order of the source sequence, as desired.