What's the best way to compile a list of all Parent objects of a list of child objects?

StackOverflow https://stackoverflow.com/questions/23450937

  •  15-07-2023
  •  | 
  •  

Pregunta

Suppose I have a child and parent class like this:

public Parent
{
    public ID {get; set;}
    public Name {get; set;}
    public ICollection<Child> Children {get; set;}
}

public Child
{
    public ID {get; set;}
    public Name {get; set;}
    public ICollection<Parent> Parents {get; set;}
}

What is the best way (using linq or otherwise) to compile a list of all the Parents or all the Children of a ICollection<Child> or a List<Child>?

¿Fue útil?

Solución

I interpeted this as a way to get all the parents of a given list of children.

IEnumerable<Parent> parents = childList.SelectMany(c => c.Parents).Distinct();

Otros consejos

Something like this

from p in Parents
where p.Children.Any(Function(x) ChildList.Contains(x))
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top