C#linq in Dictionary

我有一个对象allStudents = Dictionary<ClassRoom, List>()

在Linq,我如何获得所有男性学生的名单? (student.Gender ==“m”)来自所有课堂?

伊恩

请尝试以下方法

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

这方面的技巧是SelectMany操作。 它具有将List的集合展平为单个Student集合的效果。 结果列表与您从前到后排列每个列表的方式相同。

您可以使用嵌套的from子句。 第一个from他们的学生(词典中的项目)中选择所有课程,表示为KeyValuePair> 。 然后,您可以使用Value属性选择课程中的所有学生并过滤它们:

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

在封面下,嵌套的from子句被转换为SelectMany方法调用。