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

标签 c# .net linq lambda

如果我有 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/

相关文章:

c# - 为什么在我的 WebClient DownloadFileAsync 方法中下载空文件?

c# - 如何舍入到最接近的 0.5?

c# - AndAlso 之间有几个 Expression<Func<T, bool>> : referenced from scope

c# - 分层架构中的 Entity Framework ?

c# - Linq to Xml 查询

c# - 将 SQL 查询更改为 LINQ、asp.net MVC

c# - 我无法在 Razor View 中设置断点

c# - 当我完成 View 和 ViewModel 而不是 Model 时,如何删除事件处理程序

c# - 构建服务器上的 migrate.exe 想要 "start over"进行迁移

c# - .Cast<T> 扩展方法总是抛出 InvalidCastException - 你应该如何使用这个方法?