Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq GroupBy. Return top one item of a subset of data

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();
like image 247
Damo Avatar asked Mar 11 '13 15:03

Damo


2 Answers

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 
like image 83
Sergey Berezovskiy Avatar answered Oct 28 '22 10:10

Sergey Berezovskiy


  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())
like image 23
Colonel Panic Avatar answered Oct 28 '22 11:10

Colonel Panic