5

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();
Matt Busche
  • 14,216
  • 5
  • 36
  • 61
Damo
  • 361
  • 4
  • 16

2 Answers2

7
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 
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
4
  1. Group flights by destination
  2. From each group select the cheapest flight in the group

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())
Colonel Panic
  • 132,665
  • 89
  • 401
  • 465