views:

238

answers:

2

I have an object allStudents = Dictionary<ClassRoom, List<Student>>()

In Linq how would I get a list of all the students who are male? (student.Gender=="m") from all the Classrooms?

Ian

+5  A: 

Try the following

var maleStudents = allStudents
  .SelectMany(x => x.Values)
  .Where(x => x.Gender=="m");

The trick to this is the SelectMany operation. It has the effect of flattening a collection of List<Student> into a single collection of Student. The resulting list is the same as if you'd lined up each list front to back.

JaredPar
this btw, will work faster than what Tomas suggested below
vittore
Yes, the C# compiler translates the query to slightly more complicated code, but I don't think that the difference will matter in any reasonable scenario. It is more important to choose the solution that looks more readable (which is a personal opinion).
Tomas Petricek
+4  A: 

You can use nested from clause. The first from selects all classes together with their students (an item from the dictionary), which is represented as a KeyValuePair<ClassRoom, List<Student>>. Then you can select all students from the class using the Value property and filter them:

var q = from cls in allStudents
        from s in cls.Value
        where s.Gender == "M" select s;

Under the cover, the nested from clause is translated to the SelectMany method call.

Tomas Petricek