I have a table of flight price data and I want to return the top 1 cheapest flight to each destination destination. The table has the following basic fields:
FlightInfoID
AirportFrom
AirportTo
Price
I tried the following but it did not return the results I expected as there were multiple items for a specific destination and I only want 1 result per destination so if I have 50 destinations I would get 50 items returned.
lstBestFlightDealsForAllRoutes.OrderBy(p=> p.Price).GroupBy(x => x.AirportTo).First();
from f in lstBestFlightDealsForAllRoutes
group f by new { f.AirportFrom, f.AirportTo } into g // group by route
select g.OrderBy(x => x.Price).First() // select cheapest flight
Lniq makes 2 difficult (the Minimum function is useless), but you can do it (with a small performance cost) by ordering each group by price and selecting the first from each group, eg.
flights.GroupBy(f => f.Destination).Select(g => g.OrderBy(f => f.Cost)).Select(g => g.First())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With