You want to use SelectMany:
var allStudents = classes.SelectMany(c => c.Students).Distinct();
If the student objects for a single unique student are not the same, you can use the DistinctBy
recipe from this question. Or you implement IEqualityComparer
like this for the student type:
public class StudentEqualityComparer : IEqualityComparer<Student>
{
public bool Equals(Student a, Student b)
{
return a.PersonId == b.PersonId;
}
public int GetHashCode(Student s)
{
return s.PersonId.GetHashCode(); // or just `return s.PersonId`
}
}
var allStudents = classes.SelectMany(c => c.Students)
.Distinct(new StudentEqualityComparer());