由学校董事会和学校组成教师名单

时间:2013-12-02 11:22:13

标签: c# asp.net linq list lambda

我有查询返回教师名单,我需要由学校董事会和学校对他们进行分组。

实际上显示的数据如下:

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

我需要展示的内容:

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

我正在尝试使用Linq或Lambda来做这件事,我不知道这是不是最好的方法。

感谢。

1 个答案:

答案 0 :(得分:5)

按照组合键对您的实体进行分组 - 即使用新的匿名类型按教师名称和学校名称对教师进行分组:

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);
}