Bumble
Bumble

Reputation: 557

LInq querying collection inside collection

my object contains a collection of collections . i like to get all child object ids and store it in a string array.

MainObject contains List of parent

Parent contains List of Child

Child properties are (Id,Name)

how can i query MainObject and find all child ids and store it in string array using linq?

Upvotes: 7

Views: 10285

Answers (3)

Pranay Rana
Pranay Rana

Reputation: 176886

try this

var id =parents.SelectMany(p => p.Children).Select(x => x.Id).ToArray();

Upvotes: 4

LukeH
LukeH

Reputation: 269288

var arrayOfIds = MainObject.ListOfParents
                           .SelectMany(x => x.ListOfChildren)
                           .Select(x => x.Id)
                           .ToArray();

Upvotes: 3

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174289

You can use SelectMany:

var stringArray = MainObject.ListOfParent
                            .SelectMany(p => p.ListOfChildren
                                              .Select(c => c.Id.ToString()))
                            .ToArray()

Upvotes: 15

Related Questions