2016-10-04 63 views
0

我正在做一個應用程序,在該應用程序中,我給出了航班的ID,並且程序打印了該航班上所有乘客的信息。我設法做到這一點,以便我可以搜索帶有身份證件的乘客,並打印出他正在乘坐的航班信息,但我無法以其他方式進行。有小費嗎?這些是陣列:以相同的搜索條件從陣列中打印多行

Passenger[] passengers = new Passenger[] { 
      new Passenger("John", 100, 200), 
      new Passenger("Mark", 101, 200), 
      new Passenger("Charlie", 102, 201)}; 

    Flight[] flights = new Flight[] { 
      new Flight(200, "Berlin", "Moscow", "05.10.2016"), 
      new Flight(201, "Paris", "Madrid", "06.10.2016")}; 

乘客和航班具有相同的ID,所以我用它來連接數組。

回答

0

user2023861打我,但這裏是一個更完整例如使用where子句來過濾航班上的結果ID 此處完整代碼:https://github.com/drGarbinsky/PrintFlightsExample

var data = from f in flights 
        join p in passengers on f.ID equals p.Flight 
        where f.ID == searchId 
        select new { flight = f, passenger = p }; 

     if (data.Any()) 
     { 
      var format = "{0} departs {1} for {2} on flight {3} in seat {4} on {5}"; 
      foreach (var item in data) 
      { 
       Console.WriteLine(string.Format(format, item.passenger.Name, item.flight.Origin, item.flight.Destination,item.flight.ID, item.passenger.Seat, item.flight.Date)); 
      } 
     } 

輸出看起來像:

John departs Berlin for Moscow on flight 200 in seat 100 on 05.10.2016 
Mark departs Berlin for Moscow on flight 200 in seat 101 on 05.10.2016 
0

您可以將陣列通過飛行ID這樣的結合在一起:

var joined = from p in passengers 
      join f in flights on p.FlightId equals f.FlightId 
      select new { p, f }; 

然後可以遍歷這樣的:

foreach(var match in joined) { 
    Console.WriteLine("Passenger name = " + match.p.Name); 
    Console.WriteLine("Flight time = " + match.f.FlightTime); 
}