developer747
developer747

Reputation: 15958

Select one parent property and all children using linq

I have a collection of sections and each section has a collection of questions. If I want to select all the questions under all the sections, this works

Sections.SelectMany(s=>s.Questions)

But now I also want the section number. So if I try something like this

 Sections.SelectMany(s=>s.Questions,s.SectionNumber)

it throws compilation error.

How do I make this work?

Upvotes: 14

Views: 3863

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125650

You should use anonymous type here:

Sections.SelectMany(s => s.Questions, (s, q) => new { Question = q, s.SectionNumber })

Upvotes: 19

Related Questions