Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ - filter collection inside collection

Tags:

c#

linq

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.

like image 447
pedrodbsa Avatar asked Dec 27 '10 17:12

pedrodbsa


2 Answers

You're looking for

.Where(p => p.Children.All(c => !c.Gender && c.GrandChildren.All(g => !g.Gender))
like image 100
SLaks Avatar answered Sep 28 '22 07:09

SLaks


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()
})
like image 21
fejesjoco Avatar answered Sep 28 '22 07:09

fejesjoco