How do I do an integer list intersection while keeping duplicates?

后端 未结 6 1489
别跟我提以往
别跟我提以往 2020-12-31 09:11

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

6条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-31 10:03

    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.

提交回复
热议问题