Check for any element that exists in two collections

前端 未结 1 1200
独厮守ぢ
独厮守ぢ 2020-12-01 20:32

I\'m wondering if Linq has a method to check if two collections have at least a single element in common. I would expect something like this:

var listA = new         


        
相关标签:
1条回答
  • 2020-12-01 21:18

    Sounds like you just want:

    bool hasSameElements = listA.Intersect(listB).Any();
    

    EDIT: As noted in comments, Intersect uses lazy evaluation. It defers all execution until the first element is read from the result; at that point it will load all of listB into a set, and then stream listA until it finds a result to yield. At that point, Any() will return true and so no more work will be done. See my Edulinq post on Intersect for more information.

    0 讨论(0)
提交回复
热议问题