合并项目时保持同级引用

Keeping sibling reference while combining items

我有航班和航段信息,我想要航段的笛卡尔坐标和航班号信息:

class FlightSegment{
    public string FlightNumber {get;set;}
}

class Flight{
    public FlightSegment FlightSegment {get;set;}
    public List<string> FlightClass {get;set;}
}

class FlightSegmentAndFlight{
    public string FlightSegmentName {get;set;}
    public string FlightNumberName {get;set;}
}
static class Utils {
    //util for make cartesian of segments
    public static IEnumerable<IEnumerable<T>> CartesianItems<T>(this IEnumerable<IEnumerable<T>> sequences) {
        IEnumerable<IEnumerable<T>> emptyProduct =
          new[] { Enumerable.Empty<T>() };
        IEnumerable<IEnumerable<T>> result = emptyProduct;
        foreach (IEnumerable<T> sequence in sequences) {
            result = from accseq in result from item in sequence select accseq.Concat(new[] { item });
        }
        return result;
    }
}
void Main()
{
    var f1 = new Flight(){
        FlightSegment = new FlightSegment{FlightNumber = "FN1"},
        FlightClass =  new List<string> {"A1","B1"}
    };  
    var f2 = new Flight{
        FlightSegment = new FlightSegment{FlightNumber = "FN2"},
        FlightClass =  new List<string> {"A2","B2"}
    };  
    var flights = new List<Flight>{f1,f2};  
    var result = flights.Select(x => x.FlightClass).CartesianItems();
    Console.WriteLine(result);

}

结果:

A1 A2

A1 B2

B1 A2

B1 B2

我想要什么

A1, FN1
A2、FN2

A1, FN1
B2、FN2

B1, FN1
A2、FN2

B1, FN1
B2、FN2

我不允许添加现有 类 的属性,因为它们来自 wcf 参考。如何在组合航段时保留航班号信息?

我想我应该使用类似的东西:

 var result2 = flights.SelectMany(f => f.FlightClass, (f, flightSegments) => new {f, flightSegments}).
    Select(x=> new {
    x.flightSegments.CartesianItems(),
    x.f
    });

并在里面做笛卡尔

由于您只需要将航班号附加到航班 class,因此请使用匿名 class,如下所示:

public static void Main()
{
    var f1 = new Flight()
    {
        FlightSegment = new FlightSegment { FlightNumber = "FN1" },
        FlightClass = new List<string> { "A1", "B1" }
    };
    var f2 = new Flight
    {
        FlightSegment = new FlightSegment { FlightNumber = "FN2" },
        FlightClass = new List<string> { "A2", "B2" }
    };
    var flights = new List<Flight> { f1, f2 };
    var result = flights.Select(x => x.FlightClass.Select(fc => new {FlightClass = fc, FlightNumber = x.FlightSegment.FlightNumber })).CartesianItems();
    foreach (var item in result)
        Console.WriteLine(String.Join(" ", item.Select(c => c.FlightClass + " " + c.FlightNumber)));        
}