[英]include group by in c# linq query
我有這個 linq 查詢,我想按某些特定字段將其分組:
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.DestBusStationCode
和x.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 }
但是我用這種方法遇到了多個錯誤。
按某些內容分組后,您只能在選擇中包含這些屬性以及任何聚合值,例如Count
和Sum
。 這是因為您是說給我一行,其中按屬性分組的屬性相同,因此其他屬性可能具有該組的多個值。 以下將按DepartureTime
和DestBusStationCode
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 }
您不能再在結果中包含NameOfLine
、 StopOrder
和LocationId
,因為這些屬性在具有相同DepartueTime and
DestBusStationCode` 的任何給定組之間可能不同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.