c# - 产量返回 IEnumerable<IEnumerable<...>>

标签 c# linq deferred-execution

以下代码创建了 List<string> 的中间实例并在 yield 返回之前将值附加到它。有没有一种好的方法可以避免创建实例并直接 yield 返回单元格值?

IEnumerable<IEnumerable<string>> GetStrValues()
{
    ......
        foreach (var r in rows)
        {
            var row = new List<string>();
            foreach (var c in r.Cells())
            {
                var value = getCellStr(c);
                row.Add(value);
            }
            yield return row;
        }
    }
}

最佳答案

要避免创建列表,您可以使用 LINQ:

IEnumerable<IEnumerable<string>> GetStrValues()
{
     return rows.Select(r => r.Cells().Select(getCellStr));
}

这将延迟执行,即不会创建中间列表。这是避免分配您不需要的内存的好方法(除非您要在内部 IEnumerable<string> 上迭代多次,而 getCellStr 很昂贵)。

关于c# - 产量返回 IEnumerable<IEnumerable<...>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35468984/

相关文章:

linq - C# Linq SelectMany,返回整个对象

c# - 使用 linq 时从 WCF 服务返回什么?

c# - 是否值得为单个类抽象出对象创建?

c# - 如何插入带有 1 :n relationship in Azure App Service 的实体

c# - Entity Framework ,导航属性和存储库模式

python - 在 Python 中使用 lambda 进行延迟评估

c# - 缓存 Linq 查询 - 这可能吗?

c# - 如何正确删除数据库中的记录

c# - 如何编码(marshal)包含可变大小字符串的结构?

linq - 如何对动态选择的列执行不同操作?