如果我有 IEnumerable<List<string>>
类型的变量是否有 LINQ 语句或 lambda 表达式我可以应用于它,它将组合返回 IEnumerable<string>
的列表?
最佳答案
SelectMany - 即
IEnumerable<List<string>> someList = ...;
IEnumerable<string> all = someList.SelectMany(x => x);
对于 someList 中的每个项目,这然后使用 lambda“x => x”为内部项目获取 IEnumerable
然后将这些作为连续 block 返回。本质上,SelectMany 类似于(简化):
static IEnumerable<TResult> SelectMany<TSource, TResult>(
this IEnumerable<TSource> source,
Func<TSource, IEnumerable<TResult>> selector) {
foreach(TSource item in source) {
foreach(TResult result in selector(item)) {
yield return result;
}
}
}
尽管这有所简化。
关于c# - 在 Lambda/LINQ 中组合列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/150332/