在组合项目时保持兄弟参考

时间:2017-02-17 14:27:21

标签: c# linq cartesian

我有航班和航段信息,我想拥有带有航班号信息的笛卡儿段:

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
    });

并在其中做笛卡儿

1 个答案:

答案 0 :(得分:1)

由于您只需要将航班号附加到航班班,因此请使用匿名类:

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)));        
}