我有这种类的结构
飞行
..OriginDestinations
.... FlightSegments
我的问题很简单,在lambda表达式中可以相同:
var result1 = (
from sf in selectedFlights
from odo in sf.OriginDestinationOptions
from fs in odo.FlightSegments
select new FlightNumberAndClass {
FlightNumber = fs.FlightNumber,
FlightClass = fs.FlightClass
});
其中result1是IEnumerable<FlightNumberAndClass>
我尝试了这个但是:
var result2 =
selectedFlights.Select(
x => x.OriginDestinationOptions.Select(
y =>
y.FlightSegments.Select(
z => new FlightNumberAndClass {
FlightNumber = z.FlightNumber,
FlightClass = z.FlightClass
}
)
)
);
它给了我result2的类型“类似于” System.Linq.Enumerable.WhereSelectListIterator<IEnumerable<IEnumerable<FlightNumberAndClass>>>
答案 0 :(得分:2)
SelectMany
将序列的每个元素投影到IEnumerable<T>
,并将生成的序列展平为一个序列。
IEnumerable<FlightNumberAndClass> result2 = selectedFlights
.SelectMany(sf => sf.OriginDestinationOptions
.SelectMany(odo => odo.FlightSegments
.Select(fs => new FlightNumberAndClass
{
FlightNumber = fs.FlightNumber,
FlightClass = fs.FlightClass
}
)
)
);
答案 1 :(得分:0)
在这种情况下,你可以像这个例子一样使用SelectMany
:
List<List<List<string>>> list1 = new List<List<List<string>>>
{
new List<List<string>> {
new List<string>{"a","b","c","d","e"},
new List<string>{"a","b","c","d","e"},
new List<string>{"a","b","c","d","e"}
},
new List<List<string>> {
new List<string>{"a","b","c","d","e"},
new List<string>{"a","b","c","d","e"},
new List<string>{"a","b","c","d","e"}
},
new List<List<string>> {
new List<string>{"a","b","c","d","e"},
new List<string>{"a","b","c","d","e"},
new List<string>{"a","b","c","d","e"}
}
};
var result = list1.SelectMany(a => a.SelectMany(b => b.Select(c => c))).ToList();