C# linq in Dictionary<>
I have an object allStudents = Diction开发者_JAVA技巧ary<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
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.
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.
精彩评论