简体   繁体   中英

C# linq in Dictionary<>

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM