Amitabh
Amitabh

Reputation: 61187

Linq: Select First Items from the Child List?

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

Parent
   --> IList<Child>

Now, I have a List of Parent objects and I want the First Child of each parent in the list.

What is the best way to do this using Linq?

Upvotes: 4

Views: 3841

Answers (3)

jocoteco
jocoteco

Reputation: 1

parent.child.FirstOrDefault();

Upvotes: 0

VoodooChild
VoodooChild

Reputation: 9784

You can iterate each "Parent" and find the first of it's offspring:

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

Upvotes: 0

Reddog
Reddog

Reputation: 15579

parents.Where(p => p.Children.Any()).Select(p => p.Children.First());

Upvotes: 11

Related Questions