Ian*_*ink 20 c# linq dictionary
我有一个对象 allStudents = Dictionary<ClassRoom, List<Student>>()
在Linq,我如何获得所有男性学生的名单?(student.Gender =="m")来自所有课堂?
伊恩
Jar*_*Par 23
请尝试以下方法
var maleStudents = allStudents
.SelectMany(x => x.Values)
.Where(x => x.Gender=="m");
Run Code Online (Sandbox Code Playgroud)
对此的诀窍是SelectMany操作.它具有将一个集合扁平List<Student>化为单个集合的效果Student.结果列表与您从前到后排列每个列表的方式相同.
Tom*_*cek 19
您可以使用嵌套from子句.第一个from选择所有课程与他们的学生(字典中的项目),表示为a KeyValuePair<ClassRoom, List<Student>>.然后,您可以使用该Value属性选择课程中的所有学生并过滤它们:
var q = from cls in allStudents
from s in cls.Value
where s.Gender == "M" select s;
Run Code Online (Sandbox Code Playgroud)
在封面下,嵌套from子句被转换为SelectMany方法调用.