Home > Mobile >  LINQ query to return Flight object with the most passengers
LINQ query to return Flight object with the most passengers

Time:11-04

I have a ICollection _flights

The Flight Object contains the following properties:

        public Guid Id { get; }
        public string FlightNo { get; }
        public Airport DepartFrom { get; }
        public Airport ArriveAt { get; }
        public Plane AirPlane { get; set; }
        public DateTime DepartureTime { get; set; }
        public DateTime ArrivalTime { get; set; }
        public TimeSpan TotalTravelTime { get
            {
                return ArrivalTime.Subtract(DepartureTime);
            }
        }
        public IEnumerable<Booking> Bookings => _bookings;

The Booking object contains:

public DateTime BookingDate { get; }
        private ICollection<Passenger> _passengers;
        public IEnumerable<Passenger> Passengers => _passengers;

I need a Linq query that gives me the Flight object with the most passengers.

I've been running around in circles for a week now and I don't find the answer. Could someone help me in the right direction? I guess I need MaxBy on the sum of Passengers.Count in every Flight Object, but I don't understand how to get there. All help more than welcome.

CodePudding user response:

I guess I need MaxBy on the sum of Passengers.Count in every Flight Object

You've already got the answer, what's giving you trouble? This should work:

Flight mostPopular = flights.MaxBy(flight => 
    flight.Bookings.Sum(booking => 
        booking.Passengers.Count()))
  •  Tags:  
  • linq
  • Related