1

I have query that return a list of Teachers and I need to group them by School Board and School.

Actually a show the data like bellow:

School Board Name 1
School Name 1
Teacher Name 1

School Board Name 1
School Name 1
Teacher Name 2

School Board Name 1
School Name 2
Teacher Name 3

School Board Name 1
School Name 2
Teacher Name 4

What I need to show:

School Board Name 1
School Name 1
Teacher Name 1
Teacher Name 2

School Board Name 1
School Name 2
Teacher Name 3
Teacher Name 4

I'm trying using Linq or Lambda to make this, I don't know if this is the best way.

Thanks.

Mahmoud Gamal
  • 78,257
  • 17
  • 139
  • 164
williancsilva
  • 151
  • 1
  • 3
  • 12

1 Answers1

5

Group your entities by composite key - i.e. use new anonymous type to group teachers by school board name and school name:

var query = teachers.GroupBy(t => new { t.SchoolBoardName, t.SchoolName });

foreach(var schoolGroup in query)
{
   Console.WriteLine(schoolGroup.Key.SchoolBoardName);
   Console.WriteLine(schoolGroup.Key.SchoolName);

   foreach(var teacher in schoolGroup)
        Console.WriteLine(teacher.TeacherName);
}
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459