Get child objects in list of parent objects using LINQ C#

Updated on     Kisan Patel

Problem:

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 virtual ICollection Children { get; set; }
}
public class Child
{
    public int ID { get; set; }
    public int ParentID { get; set; }
    
    [ForeignKey("ParentID")]
    public virtual Parent Parent { get; set; }
}

Now I want the Child object having a specific ID:

Solution:

You need to use SelectMany projection operator:

The SelectMany operator is useful when working with a sequence of sequences.

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

Also, if you want to get the list of child objects from list of parent objects in LINQ then follow below approach:

List child_list = parents.SelectMany(parent => parent.Children).ToList();

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


LINQ

Leave a Reply