Say I have the following structure,
public class Parent
{
public string Id{get;set;}
public string Name{get;set;}
public List<Child> Children{get;set;}
}
public class Child{
public string Id{get;set;}
public string Name{get;set;}
}
and I have a list of strings containing identifiers List<string>Idsand a list of Parents List<Parent> parents. How can I filter my parents to get only the following:
- Parent whose Id is contained in identifiers along with all child elements.
- Only a child whose id is contained in the ids along with his parent.
So, if the identifiers contain the identifier of the parent, I want it with the children, and if it contains the child identifier, I want it with my parent (without the rest of the children).
, , , , , .
parents
.Where(p => ids.Contains(p.Id) ||
p.Children.Any(x=>ids.Contains(x.Id)))
.Select(res => new Parent() {
Name = res.Name,
Id = res.Id,
Children = es.Children
.Where(child => ids.Contains(child.Id))
.ToList()
});