1

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?

mas4
  • 909
  • 1
  • 8
  • 19
Ian Vink
  • 63,888
  • 100
  • 326
  • 544

2 Answers2

1

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())
Royi Namir
  • 138,711
  • 129
  • 435
  • 755
1

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());
Community
  • 1
  • 1
poke
  • 339,995
  • 66
  • 523
  • 574