LINQ query depending on grandchild collection
-
24-06-2021 - |
Question
I have a set of objects that map to my database and are populated correctly, however I have a case when I need to return a collection of objects based on a value of a grandchild object. The relationships between these objects are causing me issues to sucessfully create this linq query.
The objects are as follows:
public class Pet
{
public int PetID { get; set; }
public string Name { get; set; }
public virtual int ToyID { get; set; }
public virtual Toy Toy { get; set; }
}
public class Toy
{
public int ToyID { get; set; }
public string Name { get; set; }
public virtual ICollection<Owner> Owners { get; set; }
public virtual ICollection<Pet> Pets { get; set; }
}
public class Owner
{
public int OwnerID {get; set;}
public string Name {get; set;}
public virtual ICollection<Toy> Toys { get; set; }
}
So basically its a 1 to many to many relationship.
I have a Collection of Pets and I would like restrict depending on the Owner object's Name property.
Solution
What about this?
Pets.Where( p => p.Toy.Owners.Any(o => o.Name == "OwnerNameYourLookingFor") );
This will return an enumerable of Pets who have an OwnerNameYourLookingFor in their owner list.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow