按特定字段分组列表

时间:2013-12-10 15:55:27

标签: asp.net vb.net linq

我想显示按日期分组的课程列表。 我尝试了几件事,但我认为下面的代码是我最好的尝试。 虽然它仍然无法解决。

Public Function showSchedule(ByVal driver As Integer, month As Integer) As List(Of tbl_lesson)
    Dim result = From lesson In dc.tbl_lesson
                 Order By lesson.fk_calendar
                 Join c In dc.tbl_calendars On c.pk_calendar Equals lesson.fk_calendar
                 Join ls In dc.tbl_lessonseries On ls.pk_tbl_lessonseries  Equals  lesson.fk_tbl_lessonseries 
                 Join ts In dc.tbl_timeslots On ts.pk_timeslot Equals lesson.fk_timeslot
                 Where ls.fk_employee = Convert.ToInt16(driver) And c.month = month
                 Group lesson By lesson.fk_calendar Into grp = Group
                 Select grp

    Return result
End Function

提前感谢您的帮助! Jannick

1 个答案:

答案 0 :(得分:0)

按值分组时,会返回IGrouping<TKey, TElement>,它本质上是集合的集合(按键值分隔),但是您的函数正在尝试返回tbl_lesson的平面列表值。

如果您尝试按键值获取 distinct 列表,则可以从每个组中取出第一个值:

Return result.Select(g => g.First()).ToList();  // will return a list of tbl_lesson items

如果您只想通过键值订购,那么只需取出分组:

Dim result = From lesson In dc.tbl_lesson
             Order By lesson.fk_calendar
             Join c In dc.tbl_calendars On c.pk_calendar Equals lesson.fk_calendar
             Join ls In dc.tbl_lessonseries On ls.pk_tbl_lessonseries  Equals  lesson.fk_tbl_lessonseries 
             Join ts In dc.tbl_timeslots On ts.pk_timeslot Equals lesson.fk_timeslot
             Where ls.fk_employee = Convert.ToInt16(driver) And c.month = month
             Select grp

Return result.ToList()