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

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

    • Find the intersection of the two lists.
    • Group the lists by the intersecting items
    • Join the groups, and select the Min(Count) for each item
    • Flatten into a new list.

    See below:

    var intersect = list1.Intersect(list2).ToList();
    var groups1 = list1.Where(e => intersect.Contains(e)).GroupBy(e => e);
    var groups2 = list2.Where(e => intersect.Contains(e)).GroupBy(e => e);
    
    var allGroups = groups1.Concat(groups2);
    
    return allGroups.GroupBy(e => e.Key)
        .SelectMany(group => group
            .First(g => g.Count() == group.Min(g1 => g1.Count())))
        .ToList();
    

提交回复
热议问题