从具有相同搜索条件的数组中打印多行
本文关键字:数组 打印 条件 搜索 | 更新日期: 2023-09-27 18:11:42
我正在做一个应用程序,我给出航班的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")};
Passenger和Flight具有相同的ID,因此我使用它来链接数组。
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
您可以像这样通过航班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);
}