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

后端 未结 6 1514
别跟我提以往
别跟我提以往 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:09

    Here's one way to do it. To be fair, it is very similar to David B's answer except that it uses a join to do the association.

    IEnumerable seqA = ...
    IEnumerable seqB = ...
    
    var result = from aGroup in seqA.GroupBy(x => x)
                 join bGroup in seqB.GroupBy(x => x) 
                             on aGroup.Key equals bGroup.Key
                 let smallerGroup = aGroup.Count() < bGroup.Count() 
                                    ? aGroup : bGroup
                 from item in smallerGroup
                 select item;
    

提交回复
热议问题