在c#linq查询中包含groupby

本文关键字:包含 groupby 查询 c#linq | 更新日期: 2023-09-27 18:28:24

我有一个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 }

但我在这种方法上犯了很多错误。

在c#linq查询中包含groupby

根据某个属性分组后,您的选择中只能有这些属性加上任何聚合值,如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`的任何给定组的这些属性可能不同。