0

I have two classes, as follows:

public class Route
{
    public ObservableCollection<Flight> Flights = new ObservableCollection<Flight>();
}

public class Flight
{
    string airlineName;
}

I wish to return a list of all routes that have a flight that is operated by a specified airline.

I tried doing Routes.SelectMany(x => x.Flights).Where(x => x.Airline == airline); but that returns all the flight objects - I need the route objects...

Can anyone explain how I can do this using ObjectQuery? Thanks in advance!

Gavin Coates
  • 1,366
  • 1
  • 20
  • 44
  • Both your classes deal with Flights, so I don't see anywhere where you are getting route information where are you assigning routes – MethodMan Dec 06 '11 at 21:12

2 Answers2

4

It sounds like you want:

Routes.Where(route => route.Flights.Any(flight => flight.Airline == airline))
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • thanks for the answer, unfortunately RedHat's fingers were quicker, so I will accept his based on being first. – Gavin Coates Dec 06 '11 at 21:52
  • @GavinCoates: According to the timestamps, I actually posted the answer 31 seconds before RedHat, but I don't mind :) – Jon Skeet Dec 06 '11 at 22:34
2
Routes.Where(x =>x.Flights.Any(p=> p.Airline == airline))
Reza ArabQaeni
  • 4,848
  • 27
  • 46
  • thanks, that works and returns the expected rresult, however I am getting the following error: `Unable to cast object of type 'WhereEnumerableIterator`1[Route]' to type 'System.Collections.ObjectModel.ObservableCollection`1[Route]'.` – Gavin Coates Dec 06 '11 at 21:35
  • well, if I do `var result = ` then it works, and if I debug the `result` variable contains a collection of routes, as expected. But I need this in a function which returns a `ObservableCollection` - but casting to this fails with the error mentioned – Gavin Coates Dec 06 '11 at 21:42
  • Check this: http://stackoverflow.com/questions/3559821/how-to-convert-ienumerable-to-observablecollection – Reza ArabQaeni Dec 06 '11 at 21:45
  • Thanks, that fixed it. For reference, the returned object is a generic IEnumerable, so to convert to an ObservableCillection all you need is: `ObservableCollection collection = new ObservableCollection(result);` (where result is the result of the query in the original answer) – Gavin Coates Dec 06 '11 at 21:50