Let's say I have the following classes:
class Parent
{
bool Gender { get; set; }
List<Child> Children { get; set; }
}
class Child
{
bool Gender { get; set; }
List<Child> GrandChildren { get; set; }
}
class GrandChild
{
bool Gender { get; set; }
}
Using linq, can anyone help me filter a Parent object by returning a List<Child>
where each Child has Gender == false
and each Child's GrandChild has Gender == false
?
I've managed to return a List<GrandChild>
but I really need the hierarchy to be maintained.
You're looking for
.Where(p => p.Children.All(c => !c.Gender && c.GrandChildren.All(g => !g.Gender))
Your question is a bit vague. Here's a solution which rebuilds the children and grandchildren lists, I wasn't sure if I needed the child.GrandChildren.All(gc => !gc.Gender) so I left it out for clarity:
parents.Select(parent => new Parent
{
Gender = parent.Gender,
Children = parent.Children.Where(child => !child.Gender).Select(child => new Child
{
Gender = false,
GrandChildren = child.GrandChildren.Where(gc => !gc.Gender).ToList()
}
).ToList()
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With