Search code examples
linqselectlambdaany

Using Linq to select from a List in a List with Contains


I'm having syntax troubles.

public class Student
{
   int StudentId;
   string Name;
}

public class Course
{
   int CourseId;
   List<Student> Students;
}


int[] studentIds = { 5, 7, 12 };
List<Course> allCourses = myDataContext.Courses.ToList();

Using Lambda expressions or query expressions, how do I get a filtered list of all the Courses containing any of the Students in the array studentIds?


Solution

  • var result = from course in allCourses
                 where course.Students.Any(x => studentIds.Contains(x.StudentId))
                 select course;