简体   繁体   English

在 c# linq 查询中包含 group by

[英]include group by in c# linq query

I have this linq query which I want to include group by some specific fields:我有这个 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 }

In that linq query I want to add a group by x.DestBusStationCode and x.DepartureTime but modifying the query to something like this:在那个 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 }

But I'm getting multiple errors with that approach.但是我用这种方法遇到了多个错误。

Once you group by something you can only have those properties in your select plus any aggregate value such as Count and Sum .按某些内容分组后,您只能在选择中包含这些属性以及任何聚合值,例如CountSum This is because you are saying give me a single row where the grouped by properties are the same, so other properties may have multiple values for the group.这是因为您是说给我一行,其中按属性分组的属性相同,因此其他属性可能具有该组的多个值。 The following would group by DepartureTime and DestBusStationCode以下将按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 }

You can no longer include NameOfLine , StopOrder and LocationId in your results because these properties may differ among any given group with the same DepartueTime and DestBusStationCode`.您不能再在结果中包含NameOfLineStopOrderLocationId ,因为这些属性在具有相同DepartueTime and DestBusStationCode` 的任何给定组之间可能不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM