Linq: select First Items from the Child list?

I have the following one-to-many relationship between two objects.

Parent --> IList<Child> 

Now I have a List of Parents , and I want the first child of each parent in the list.

What is the best way to do this with Linq?

+4
source share
3 answers
 parents.Where(p => p.Children.Any()).Select(p => p.Children.First()); 
+11
source

You can iterate through each "parent" and find the first of its descendants:

 parent.FirstOrDefault(child => parent.Children.First()); 
0
source

parent.child.FirstOrDefault ();

0
source

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


All Articles