You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

API集成中基于LINQ MVC按中转行程分组航班列表的需求

Solution: Grouping Flight Segments into Itineraries with LINQ in MVC

To solve this problem, we need to group flight segments into valid itineraries that start at CMB and end at DEL, including alternative flights for each segment in the path. Here's a step-by-step implementation using LINQ and recursive path finding:


Step 1: Define the Flight Model

First, we'll use your existing Flight class:

public class Flight {
    public string Origin { get; set; }
    public string Destination { get; set; }
    public string FlightNumber { get; set; }
    public string Provider { get; set; }
}

Step 2: Implement the Logic in an MVC Controller

In your controller, we'll:

  1. Create the flight data list
  2. Map origins to their departing flights for quick lookup
  3. Find all valid paths from CMB to DEL
  4. Build itineraries by collecting flights for each segment in the paths
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

public class FlightController : Controller
{
    public ActionResult Index()
    {
        // Initialize your flight data
        var flights = new List<Flight> {
            new Flight { Origin = "CMB", Destination = "MAA", FlightNumber = "123", Provider = "p" },
            new Flight { Origin = "MAA", Destination = "DEL", FlightNumber = "543", Provider = "p" },
            new Flight { Origin = "MAA", Destination = "DEL", FlightNumber = "320", Provider = "p" },
            new Flight { Origin = "CMB", Destination = "BOM", FlightNumber = "644", Provider = "p" },
            new Flight { Origin = "BOM", Destination = "DEL", FlightNumber = "233", Provider = "p" },
            new Flight { Origin = "CMB", Destination = "KMG", FlightNumber = "233", Provider = "p" },
            new Flight { Origin = "KMG", Destination = "PEK", FlightNumber = "233", Provider = "p" },
            new Flight { Origin = "PEK", Destination = "DEL", FlightNumber = "233", Provider = "p" }
        };

        string searchingOrigin = "CMB";
        string searchingDestination = "DEL";

        // Map each origin airport to its list of departing flights
        var originToFlights = flights.GroupBy(f => f.Origin)
                                     .ToDictionary(g => g.Key, g => g.ToList());

        // Find all valid paths from origin to destination
        var allPaths = FindAllPaths(searchingOrigin, searchingDestination, originToFlights);

        // Build itineraries by collecting flights for each segment in the path
        var transitSegmentList = allPaths
            .Select(path => 
                path.Zip(path.Skip(1), (origin, dest) => new { Origin = origin, Destination = dest })
                    .SelectMany(segment => flights.Where(f => f.Origin == segment.Origin && f.Destination == segment.Destination))
                    .ToList()
            )
            .ToList();

        // Pass the grouped itineraries to the view
        return View(transitSegmentList);
    }

    // Helper method to find all simple paths (no cycles) between two airports
    private static List<List<string>> FindAllPaths(string start, string end, Dictionary<string, List<Flight>> originToFlights)
    {
        var paths = new List<List<string>>();
        var visited = new HashSet<string>();
        FindPathsRecursive(start, end, new List<string> { start }, visited, originToFlights, paths);
        return paths;
    }

    // Recursive helper to traverse paths
    private static void FindPathsRecursive(string current, string end, List<string> currentPath, HashSet<string> visited, Dictionary<string, List<Flight>> originToFlights, List<List<string>> paths)
    {
        if (current == end)
        {
            paths.Add(new List<string>(currentPath));
            return;
        }

        if (!originToFlights.ContainsKey(current))
            return;

        visited.Add(current);

        foreach (var flight in originToFlights[current])
        {
            if (!visited.Contains(flight.Destination))
            {
                currentPath.Add(flight.Destination);
                FindPathsRecursive(flight.Destination, end, currentPath, visited, originToFlights, paths);
                currentPath.RemoveAt(currentPath.Count - 1);
            }
        }

        visited.Remove(current);
    }
}

How It Works

  1. Origin-to-Flight Mapping: The dictionary originToFlights lets us quickly access all flights leaving a specific airport, which speeds up path traversal.
  2. Path Finding: The recursive FindAllPaths method explores all valid, cycle-free routes from CMB to DEL, returning sequences like [CMB, MAA, DEL] or [CMB, KMG, PEK, DEL].
  3. Itinerary Building: For each path, we use Zip to pair consecutive airports (e.g., CMB & MAA), then collect all flights matching that segment. This groups alternative flights (like the two MAA->DEL segments) into the correct itinerary.

Result

The transitSegmentList will match your desired structure:

  • First Itinerary: [CMB->MAA, MAA->DEL(543), MAA->DEL(320)]
  • Second Itinerary: [CMB->BOM, BOM->DEL]
  • Third Itinerary: [CMB->KMG, KMG->PEK, PEK->DEL]

Content of the question来源于stack exchange,提问作者isuru

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:48:57