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
  • 989
  • 1
  • 8
  • 20
Ian Vink
  • 66,960
  • 104
  • 341
  • 555

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
  • 144,742
  • 138
  • 468
  • 792
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
  • 369,085
  • 72
  • 557
  • 602