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

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...