Anandh_Techie
Anandh_Techie

Reputation: 109

Filter List collection based on property of child list contains a name

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.

Upvotes: 2

Views: 6858

Answers (1)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37113

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

Upvotes: 10

Related Questions