Conditions may not be correct: LINQ Select which will return the entire intermediate object based on the child subtype

I'm not sure how to phrase the question correctly, so I couldn't find it. Please consider the following classes:

public class Parent
{
    public int ID { get; set; }
    public List<Child> Children { get; set; }
}

public class Child
{
    public int ID { get; set; }
    public List<subChild> subChildren { get; set;}
}

public class subChild
{
    public int ID { get; set; }
    public string Type { get; set;}
}

      

I want the linq query to return a list of all parents who have at least one Child-> subchild of a certain type, but not necessarily where they ONLY have sub-subchilds of that type.

Example:

Parent A
  - Child Xa
     - subchild 1a type="foo" 
     - subchild 2a type = "bar"
  - Child Ya
     - subchild 1a type="foo"
Parent B
  - Child Xb
     - subchild 1b type = "foo"
Parent C
  - Child Xc
     - subChild 1c type = "Bar"

      

Here's what I got (obviously wrong. My version is compiled, in case no problem)

Parents.Children.SelectMany(s => s.Subchildren).where(x => x.Type="Foo").Tolist();

      

My real implementation is slightly different and maybe my pseudo code will work as I want, but I want the parent and B to return if I search for subChild.type = "Foo".

+3


source to share


1 answer


You can use Any

:

Parents.Where(p => p.Children.Any(
    c => c.Subchildren.Any(s => s.Type == "Foo"))).ToList();

      

Don't forget that to test for equality, you need ==

instead =

.



To get a list of all children you need something like

Parents.SelectMany(p => p.Children).SelectMany(c => c.Subchildren)
    .Where(s => s.Type == "Foo").ToList();

      

0


source







All Articles