我正试图将这个精确的SQL查询转换为A和B之间不同的飞行路径:
SELECT F1.DepartingFromId, F1.ArrivingAtId
FROM dbo.Flights AS F1
WHERE F1.DepartingFromId = 1
GROUP BY F1.ArrivingAtId, F1.DepartingFromId
如果我在上面的SQL中使用foreach (airport in airports)
,它将得到一个不同路径的列表,例如,从a到b只有一条路径。
到目前为止,我有:
var dc = from flight in _DbContext.Flights
where flight.DepartingFromId == airport.Id
group flight by flight.ArrivingAtId
into flightGroup
select flightGroup;
foreach (var flightGroup in dc)
{
foreach (var flight in flightGroup)
{
distinctFlights.Add(new DistinctConnection(flight.DepartingFromId, flight.ArrivingAtId));
}
}
但是,这是返回数据库中的所有航班。大概有20万行。应该有大约70个不同的连接。
任何帮助将非常感激,因为我是新的LINQ/Lambda
在我看来,这将是一个更清晰的方式-它避免了不必要的分组:
distinctFlights.AddRange(
(
from flight in _DbContext.Flights
where flight.DepartingFromId == airport.Id
select flight.ArrivingAtId
)
.Distinct()
.ToArray()
.Select(x => new DistinctConnection(airport.Id, x)));
这也应该在数据库中生成一个有效的查询。
我不明白为什么这会返回所有航班,因为您正在过滤where
条件flight.DepartingFromId == airport.Id
。
要得到不同的,选择
- 组键值(
g.Key
)为ArrivingAtId
- 您在
where
子句中过滤的DepartingFromId
(即airport.Id
)
:
// Query for distinct connections from `airport.Id`.
var results =
from flight in _DbContext.Flights
where flight.DepartingFromId == airport.Id
group flight by flight.ArrivingAtId into g
select new DistinctConnection(airport.Id, g.Key);
// Add them to the list.
distinctFlights.AddRange(results);