在c#linq查询中包含group by

时间:2014-10-30 16:27:06

标签: c# linq linq-to-sql linq-to-entities linq-to-objects

我有这个linq查询,我希望在某些特定字段中包含group:

 from x in db.Schedule
 join y in db.Schedule on x.ID equals y.ID - 1
 join z in db.Locations on x.Line.ToString() + '-' + x.Expedition equals z.LocationCode
 where Convert.ToInt32(y.StopOrder) >= Convert.ToInt32(x.StopOrder) && x.NameOfTown == departingBusStation && dest.Contains(x.Line)
 where x.NameOfTown == departingBusStation
 select new { x.NameOfLine, x.DepartureTime, x.DestBusStationCode, x.StopOrder, z.LocationID }

在该linq查询中,我想按x.DestBusStationCodex.DepartureTime添加一个组,但将查询修改为以下内容:

 from x in db.Schedule
 join y in db.Schedule on x.ID equals y.ID - 1
 join z in db.Locations on x.Line.ToString() + '-' + x.Expedition equals z.LocationCode
 where Convert.ToInt32(y.StopOrder) >= Convert.ToInt32(x.StopOrder) && x.NameOfTown == departingBusStation && dest.Contains(x.Line)
 where x.NameOfTown == departingBusStation
 orderby x.DepartureTime ascending
 group x by new {x.DepartureTime, x.DestBusStationCode}
 select new { x.NameOfLine, x.DepartureTime, x.DestBusStationCode, x.StopOrder, z.LocationID }

但是我用这种方法得到了多个错误。

1 个答案:

答案 0 :(得分:0)

按照某些内容进行分组后,您只能在选择中添加这些属性以及CountSum等任何聚合值。这是因为你说给我一行,其中按属性分组是相同的,因此其他属性可能有多个组的值。以下内容将按DepartureTimeDestBusStationCode

分组
from x in db.Schedule
                 join y in db.Schedule on x.ID equals y.ID - 1
                 join z in db.Locations on x.Line.ToString() + '-' + x.Expedition equals z.LocationCode
                 where Convert.ToInt32(y.StopOrder) >= Convert.ToInt32(x.StopOrder) && x.NameOfTown == departingBusStation && dest.Contains(x.Line)
                 where x.NameOfTown == departingBusStation
                 orderby x.DepartureTime ascending
                 group x by new {x.DepartureTime, x.DestBusStationCode} grp
                 select new { grp.Key.DepartureTime, grp.Key.DestBusStationCode }

您的结果中不能再包含NameOfLineStopOrderLocationId,因为这些属性在具有相同DepartueTime and DestBusStationCode`的任何给定组中可能会有所不同。