I have a code that i have to do it through LINQ
var airlineNameList = new List<string>();
foreach (DTTrip trip in contract_.Trips)
{
foreach (DTFlight flight in trip.ListOfFlights)
{
airlineNameList.Add(flight.AirLineName);
}
}
How can do it through LINQ. Note: contract_ is the o开发者_如何学Gobject of class.
Please Help..
var airlineNameList = contract_.Trips
.SelectMany(t => t.ListOfFlights)
.Select(f => f.AirLineName);
var resultList = contract_.Trips
.Cast<DTTrip>()
.SelectMany(trip => trip.ListOfFlights.Cast<DTFlight>())
.Select(flight => flight.AirLineName)
.ToList();
Don't you also need Distinct
?
var airlineNameList = (
from trip in contract_.Trips
from flight in trip.ListOfFlights
select flight.AirLineName)
.ToList();
The C# foreach does implicit casting for you (which is yuck), so perhaps you need this:
var airlineNameList = (
from trip in contract_.Trips.Cast<DTTrip>()
from flight in trip.ListOfFlights.Cast<DTFlight>()
select flight.AirLineName)
.ToList();
精彩评论