Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find child objects in list of parent objects using LINQ

Tags:

c#

linq

Given a list of Parent objects that each have a list of Child objects, I want to find the child object matching a specific ID.

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

public class Child
{
    public int ID { get; set; }
}

Now I want the Child object having a specific ID:

List<Parent> parents = GetParents();
Child childWithId17 = ???

How can I do this using Linq?

like image 245
matk Avatar asked Apr 30 '13 10:04

matk


2 Answers

I think you want:

Child childWithId17 = parents.SelectMany(parent => parent.Children)
                             .FirstOrDefault(child => child.ID == 17);

Note that this assumes that Parent's Children property won't be a null-reference or contain null Child references.

like image 105
Ani Avatar answered Nov 07 '22 14:11

Ani


You can use SelectMany:

Child childWithId17 = parents.SelectMany(p => p.Children)
                             .Where(ch=>ch.ID==17)
                             .FirstOrDefault();
like image 21
Alex Avatar answered Nov 07 '22 15:11

Alex