Find all intersecting data, not just the unique values

前端 未结 4 437
孤城傲影
孤城傲影 2021-01-11 13:52

I thought that I understood Intersect, but it turns out I was wrong.

 List list1 = new List() { 1, 2, 3, 2, 3};
 List<         


        
4条回答
  •  花落未央
    2021-01-11 14:18

    Maybe this could help: https://gist.github.com/mladenb/b76bcbc4063f138289243fb06d099dda

    The original Except/Intersect return a collection of unique items, even though their contract doesn't state so (e.g. the return value of those methods isn't a HashSet/Set, but rather IEnumerable), which is probably a result of a poor design decision. Instead, we can use more intuitive implementation, which returns as much of the same elements from the first enumeration as there are, not just a unique one (using Set.Contains).

    Further more, mapping function was added in order to help intersect/except collections of different types.

    If you don't need to intersect/except collections of different types, just inspect the source code of the Intersect/Except and change the part which iterates through the first enumeration to use Set.Contains instead of Set.Add/Set.Remove.

提交回复
热议问题