Find child objects in parent list using LINQ

Given a list of parent objects, each of which has a list of child objects, I want to find a child object that matches a specific identifier.

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 to have a specific ID:

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

How to do it with Linq?

+6
source share
2 answers

I think you want:

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

Note that this assumes that the Parent Children property will not refer to null or contain Child null references.

+17
source

You can use SelectMany:

 Child childWithId17 = parents.SelectMany(p => p.Children) .Where(ch=>ch.ID==17) .FirstOrDefault(); 
+6
source

Source: https://habr.com/ru/post/943956/


All Articles