Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

Example:

public class Student
{
    int Id;
    List<subject> SubjectList;
    string Name;
}

public class Subject
{
    int Id;
    string Name;
}

List<Student> studentList = new List<Student>();

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

Where is the problem?

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

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") 
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...