I have flight and segments info and I want to have cartesian of segments with flight number info:
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);
}
results:
A1 A2
A1 B2
B1 A2
B1 B2
What I would like to have
A1, FN1
A2, FN2
A1, FN1
B2, FN2
B1, FN1
A2, FN2
B1, FN1
B2, FN2
I am not allowed to add properties of existent classes as they are coming from wcf reference. How can I keep flight number info while combining segments?
I could guess I should use something like:
var result2 = flights.SelectMany(f => f.FlightClass, (f, flightSegments) => new {f, flightSegments}).
Select(x=> new {
x.flightSegments.CartesianItems(),
x.f
});
and do cartesian in it
Since all you want is just attach flight number to flight class, use anonymous class for that like this:
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)));
}