基于子列表属性的过滤器列表集合包含一个名称 [英] Filter List collection based on property of child list contains a name

查看:72
本文介绍了基于子列表属性的过滤器列表集合包含一个名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当子列表的元素包含name时,我希望使用LinQ查询来过滤列表集合.在此,父项的子项列表应满足包含条件,并且那些子项列表仅包含在父项列表中.

I want to have LinQ query to filter list collection , when element of child list contains a name . Here child list of parent should be meet the contains criteria and those child list only included with parent list.

示例:

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的Studentlist,其中仅包含数学.

Here I want a LINQ query to filter only StudentList of SubjectList, which subject name should be contains "maths" and result must be studentlist with subjectlist, which is only contains maths.

推荐答案

问题出在哪里?

var mathStudents = StudentList.Where(x => x.SubjectList.Any(y => y.Name == "maths"));

StudentList返回所有在SubjectList中具有至少一个SubjectNamemaths的元素.

Returns all the elements from StudentList that have at least one Subject in their SubjectList whose Name is maths.

如果只想让每个学生参加数学课程,则可以使用以下方法:

If you want only the maths-courses of every student you may use this:

var mathCourses = mathStudents.Select(x => new 
{ 
    x.Student, 
    Math = x.SubjectList.Where(y => y.Name == "maths") 
});

这篇关于基于子列表属性的过滤器列表集合包含一个名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆