Linq how to select a parent from a collection where the parent contains children in another collection

I have an observable collection, i.e. Owners and this collection has children, i.e. Dogs

Now another collection of local dogs is given, how can I select all Owners with Dogs in my local Dogs collection. The condition for equality would be that Dog == Dog.

+4
source share
1 answer

The next line should do the trick. This will give you all the owners where at least one of their dogs is on the local list.

owners.Where(owner => owner.Dogs.Any(dog => localDogs.Contains(dog))) 

If you only need owners where all of their dogs are on the local list, use the following.

 owners.Where(owner => owner.Dogs.All(dog => localDogs.Contains(dog))) 

A Tiny Difference - Any() vs. All() .

+5
source

Source: https://habr.com/ru/post/1300337/


All Articles