What Was I Thinking?

Follies & Foils of .NET Development
posts - 95 , comments - 352 , trackbacks - 0

QuickTip: Selecting Children from a Parent Item in Linq

I’m posting this here because I keep forgetting the syntax, and thought others might benefit as well.

 

Given :

public class ParentItem

{

   IEnumerable<ChildItem> Children

}

 

Selecting all the childitem instances from an IEnumerable<ParentItem>:

var allChildren = ParentItems.SelectMany(parent=>parent.Children);

 

Selecting matching childItem instances from an IEnumerable<ParentItem>:

var selectedChildren = ParentItems.SelectMany(parent=>parent.Children).Where(child=><boolean expression for filtering children>)

Print | posted on Tuesday, March 29, 2011 3:47 PM | Filed Under [ Visual Studio ]

Feedback

Gravatar

# re: QuickTip: Selecting Children from a Parent Item in Linq

Here's my favorite SelectMany overload:

var query =
petOwners
.SelectMany(petOwner => petOwner.Pets, (petOwner, petName) => new { petOwner, petName })
.Where(ownerAndPet => ownerAndPet.petName.StartsWith("S"))
.Select(ownerAndPet =>
new
{
Owner = ownerAndPet.petOwner.Name,
Pet = ownerAndPet.petName
}
);
3/31/2011 2:49 AM | Ryan
Post A Comment
Title:
Name:
Email:
Comment:
Verification:
 

Powered by: