代码,我必须通过LINQ

时间:2011-03-23 15:19:17

标签: linq linq-to-objects

Error after implementing the solution

我有一个代码,我必须通过LINQ

来完成
var airlineNameList = new List<string>();

foreach (DTTrip trip in contract_.Trips)
{
    foreach (DTFlight flight in trip.ListOfFlights)
    {
        airlineNameList.Add(flight.AirLineName);
    }
}

如何通过LINQ实现。 注意:contract_是类的对象。

请帮助..

3 个答案:

答案 0 :(得分:4)

var airlineNameList = contract_.Trips
                               .SelectMany(t => t.ListOfFlights)
                               .Select(f => f.AirLineName);

答案 1 :(得分:2)

var resultList = contract_.Trips
      .Cast<DTTrip>()
      .SelectMany(trip => trip.ListOfFlights.Cast<DTFlight>())
      .Select(flight => flight.AirLineName)
      .ToList();

您是否还需要Distinct

答案 2 :(得分:1)

var airlineNameList = (
    from trip in contract_.Trips
    from flight in trip.ListOfFlights
    select flight.AirLineName)
    .ToList();

C#foreach为你做了隐式投射(这很糟糕),所以也许你需要这个:

var airlineNameList = (
    from trip in contract_.Trips.Cast<DTTrip>()
    from flight in trip.ListOfFlights.Cast<DTFlight>()
    select flight.AirLineName)
    .ToList();