gwin003
gwin003

Reputation: 7982

Query for List within List

I have a list of classrooms, each classroom has a list of students. How can I get a list of all the classrooms that have a student named Bob?

I tried:

var bobClassrooms = allClassrooms.SelectMany(x => x.Students)
                                 .Where(y => y.FirstName == "Bob");

But this returns me a list of students whose first name is Bob. How can I get this to be the list of classrooms?

Upvotes: 0

Views: 64

Answers (2)

Claudio Redi
Claudio Redi

Reputation: 68440

This should work

var bobClassrooms = allClassrooms
     .Where(x => 
         x.Students.Any(y => y.FirstName == "Bob")
     );

Upvotes: 2

MarcinJuraszek
MarcinJuraszek

Reputation: 125660

Use Any:

var bobClassrooms = allClassrooms.Where(x => x.Students.Any(y => y.FirstName == "Bob"));

Upvotes: 3

Related Questions