Daniel Hamilton
Daniel Hamilton

Reputation: 15

C# LINQ Group by

I'm new to C# and trying to answer some LINQ questions. I'm stuck on 1st marked as difficult...

Q: What were the top 10 origin airports with the largest average​ departure delays, including the values of these delays? (Hint: use group by)?

I have a list named "Flights" populated with more than 20000 objects of class "FlightInfo".

Properties of the FlightInfo class are: string Carrier, string Origin, string Destination, int DepartureDelay, int ArrivalDelay, int Cancelled, int Distance.

I understand that I should group FlightInfo by FlightInfo.Origin and than average each of these groups by FlightInfo.DepartureDelay and than show 10 with the highest average delay, but beside grouping I'm completely stuck on how to proceed further.

Thank you in advance for any help!


Here is the example of one of previous questions that I was able to answer:

Q: The weighted arrival delay of a flight is its arrival delay divided the distance. What  was the flight with the largest weighted arrival delay out of Boston, MA?

A:

var weighted = (from FlightInfo in Flights
               where FlightInfo.Origin == "Boston MA"
               orderby (FlightInfo.ArrivalDelay / FlightInfo.Distance) descending
               select FlightInfo).Take(1);

Upvotes: 1

Views: 4474

Answers (3)

Robert
Robert

Reputation: 2543

var topTen = flights.
            GroupBy(g => g.Origin).
            Select(g => new { Origin = g.Key, AvgDelay = g.ToList().Average(d => d.DepartureDelay) }).
            OrderByDescending(o => o.AvgDelay).
            Take(10);

Upvotes: 1

Hari Prasad
Hari Prasad

Reputation: 16986

You could do this.

var top10 = Flights.GroupBy(g=>g.Origin) // groupby origin 
                  .OrderByDescending(x=> x.Sum(f=> f.ArrivalDelay / f.Distance))  // Get the weighted delay for each fight and use for ordering.
                  .Select(x=>x.Key)  //Airport or Origin (Modify with what you want)
                  .Take(10)
                  .ToList() ;

Upvotes: 0

Cheng Chen
Cheng Chen

Reputation: 43531

var result = flights
    .GroupBy(f => f.Origin)
    .OrderByDescending(g => g.Average(f => f.DepartureDelay))        
    .Take(10)
    .Select(g => new
    {
        AirportName = g.Key,
        Flights = g.ToList()
    });

The last .Select parameter depends on what you want.

Upvotes: 0

Related Questions