Reputation: 68830
I have a List of classes where each class has a List of students.
I need to get a full list of students, but unique on the student.personid
allPeopleUnique= classes.Select(c=> c.Students.Select( persons ??)).Unique(student.PersonId)
Any ideas?
Upvotes: 1
Views: 295
Reputation: 388383
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());
Upvotes: 1
Reputation: 148744
If you want all the students - in a flat list with distinct values (personid):
allPeopleUnique = classes.SelectMany(c=> c.Students)
.GroupBy(p => p.personid )
.Select(g => g.First())
Upvotes: 1