-2

我必须采取什么方法来制作类似下面的方法IEnumerable<Flight>而不是字符串?我想IEnumerable<Flight>使用方法中编写的条件来操作我的源(在参数中),并IEnumerable<Flight>仅基于这些条件返回。因此,如果不满足这些条件,我不会IEnumerable<Flight>返回该项目的记录。

public string FilterFlights(IEnumerable<Flight> flights)
{
    string s = "";
    foreach (var flight in flights)
    {
        var indexItem = 0;
        DateTime previousArrivalDateTime = new DateTime();
        TimeSpan timeSpan;

        int time = 0;
        foreach (var segments in flight.Segments)
        {
            if (indexItem == 0)
            {
                previousArrivalDateTime = segments.ArrivalDate;
                s = s + "Departure: " + segments.DepartureDate + ", Arrival: " + segments.ArrivalDate + "; ";
            }

            if (indexItem > 0)
            {
                timeSpan = segments.DepartureDate - previousArrivalDateTime;
                time += timeSpan.Hours;
                s = s + "Departure: " + segments.DepartureDate + ", Arrival: " + segments.ArrivalDate + "; ";
                previousArrivalDateTime = segments.ArrivalDate;
            }
            indexItem++;
        }

        if (time > 2)
            Console.WriteLine(s);
    }

    return s;
}

课程:

    public class Flight
{
    public IList<Segment> Segments { get; set; }
}

public class Segment
{
    public DateTime DepartureDate { get; set; }
    public DateTime ArrivalDate { get; set; }
}

谢谢!

4

1 回答 1

1

您应该返回 aIEnumerable<T>并调用yield return T;

例如

public IEnumerable<string> FilterFlights(IEnumerable<Flight> flights)
{
    foreach (var flight in flights)
    {
        var indexItem = 0;
        DateTime previousArrivalDateTime = new DateTime();
        TimeSpan timeSpan;

        int time = 0;
        foreach (var segments in flight.Segments)
        {
            if (indexItem == 0)
            {
                previousArrivalDateTime = segments.ArrivalDate;
                yield return "Departure: " + segments.DepartureDate + ", Arrival: " + segments.ArrivalDate + "; ";
            }

            if (indexItem > 0)
            {
                timeSpan = segments.DepartureDate - previousArrivalDateTime;
                time += timeSpan.Hours;
                yield return "Departure: " + segments.DepartureDate + ", Arrival: " + segments.ArrivalDate + "; ";
                previousArrivalDateTime = segments.ArrivalDate;
            }
            indexItem++;
        }
    }

} 

这样你就可以像这样使用它:

我希望这是你想要的。

foreach(string text in FilterFlights(flights))
    Console.WriteLine(text);
于 2013-08-31T21:20:39.380 回答