Linq GroupBy. Pull up one element of a subset of data

I have a flight pricing data table, and I want to return the 1 cheapest flight for each destination. The table has the following main fields:

FlightInfoID
AirportFrom
AirportTo
Price

I tried the following, but did not respond to the expected results, since there were several elements for a particular place, and I only need 1 result for each destination, so if I have 50 destinations, I get 50 returned elements.

lstBestFlightDealsForAllRoutes.OrderBy(p=> p.Price).GroupBy(x => x.AirportTo).First();
+5
source share
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 
+7
source
  • Destination group flights
  • From each group, select the cheapest flight in the group

Lniq 2 ( ), ( ), , .

flights.GroupBy(f => f.Destination).Select(g => g.OrderBy(f => f.Cost)).Select(g => g.First())
+4

All Articles