gpt4 book ai didi

c# - 在 Lambda/LINQ 中组合列表

转载 作者:可可西里 更新时间:2023-11-01 03:04:28 24 4
gpt4 key购买 nike

如果我有 IEnumerable<List<string>> 类型的变量是否有 LINQ 语句或 lambda 表达式我可以应用于它,它将组合返回 IEnumerable<string> 的列表?

最佳答案

SelectMany - 即

        IEnumerable<List<string>> someList = ...;
IEnumerable<string> all = someList.SelectMany(x => x);

对于 someList 中的每个项目,这然后使用 lambda“x => x”为内部项目获取 IEnumerable 。在这种情况下,每个“x”都是一个 List ,它已经是 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com