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

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

    I wrote this extension to solve the problem:

    public static IEnumerable Supersect(this IEnumerable a, ICollection b)
                  => a.Where(t => b.Remove(t));
    

    example:

    var a = new List { 1, 2, 2, 2, 3, 3, 4, 5 };
    var b = new List { 1, 1, 2, 2, 3, 3, 3, 4, 4};
    
    var result = a.Supersect(b);
    

    result:

    { 1, 2, 2, 3, 3, 4 }
    

提交回复
热议问题