0

列表问题

我有一个很长的列表,其中包含从 Linq 到 SQL 查询中获得的船只,但我只想要每个 ImoNo 一行。今天我每个 ImoNo 大约有 4 行。我只需要最后更新的一行(所以在这个例子中我需要 2013-01-27)。

这是我的 Linq To SQL 查询:

var res = from positions in context.Lloyds_ETAs
          join vessels in context.Lloyds_Vessels on positions.ImoNumber equals vessels.imo_no
           select new PositionData {
              ImoNo = positions.ImoNumber,
              PositionCordinates = positions.AIS_Latest_Position,
              CompassOverGround = positions.Compass_over_Ground_Heading,
              VesselId = positions.Vessel_ID,
              Equipment = vessels.vessel_type,
              Updated = positions.Last_Place_Location
           };

return res.ToList();
4

4 回答 4

2
var res = (from positions in context.Lloyds_ETAs
          join vessels in context.Lloyds_Vessels on positions.ImoNumber equals vessels.imo_no
          select new PositionData {
              ImoNo = positions.ImoNumber,
              PositionCordinates = positions.AIS_Latest_Position,
              CompassOverGround = positions.Compass_over_Ground_Heading,
              VesselId = positions.Vessel_ID,
              Equipment = vessels.vessel_type,
              Updated = positions.Last_Place_Location
           })
           .GroupBy(x => x.ImoNo)
           .Select(g => g.OrderByDescending(pd => pd.Updated).First());
于 2013-02-14T18:54:16.943 回答
0

如果你想要最后一个,你所要做的就是.OrderBy(pd => pd.Updated).Last()在你的选择之后追加。

var res = (from positions in context.Lloyds_ETAs
          join vessels in context.Lloyds_Vessels on positions.ImoNumber equals vessels.imo_no
           select new PositionData {
              ImoNo = positions.ImoNumber,
              PositionCordinates = positions.AIS_Latest_Position,
              CompassOverGround = positions.Compass_over_Ground_Heading,
              VesselId = positions.Vessel_ID,
              Equipment = vessels.vessel_type,
              Updated = positions.Last_Place_Location
           }).OrderBy(pd => pd.Updated).Last();

return res.ToList();
于 2013-02-14T18:48:20.453 回答
0
(yourQuery).OrderByDescending(pd=>pd.Updated).First()
于 2013-02-14T18:50:16.287 回答
0

结果有几种方法可以只获得一个“行”:

res.OrderByDescending(x => x.Updated).Take(1);
res.OrderByDescending(x => x.Updated).First();
res.Order(x => x.Updated).Last();

看起来你有一些重复,所以也许做一个 group by 会更合适。

于 2013-02-14T18:50:21.043 回答