[英]Filter List collection based on property of child list contains a name
当子列表的元素包含名称时,我想使用LinQ查询来过滤列表集合。 在此,父级的子级列表应满足包含条件,并且这些子级列表仅包含在父级列表中。
例:
public class Student
{
int Id;
List<subject> SubjectList;
string Name;
}
public class Subject
{
int Id;
string Name;
}
List<Student> studentList = new List<Student>();
在这里,我希望LINQ查询仅过滤SubjectList的StudentList,该SubjectList的名称应包含“数学”,并且结果必须是带有Subjectlist的Studentlist,其中仅包含数学。
问题出在哪儿?
var mathStudents = StudentList.Where(x => x.SubjectList.Any(y => y.Name == "maths"));
从StudentList
返回所有在其StudentList
中具有至少一个Subject
SubjectList
其Name
为maths
的元素。
如果您只想要每个学生的数学课程,则可以使用以下方法:
var mathCourses = mathStudents.Select(x => new
{
x.Student,
Math = x.SubjectList.Where(y => y.Name == "maths")
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.