c# - IEnumerable 理解与返回集合类型

标签 c# list-comprehension

在任何情况下,当出现以下情况时:

public IEnumerable<Foo> Foobar (Bar bar)
{
    List<Foo> result = new List<Foo>()
    foreach(var Qux in bar.QuxSource)
    {
        Foo item;
        ... //a procudure that is intricate enough not to be clearly repressentable with a LINQ method
        result.Add(item);
        ... //The aforementioned inticate proceduce continues. Possiblily adding more items to result
    }
    return result;
}

优于:

public IEnumerable<Foo> Foobar (Bar bar)
{
    foreach(var Qux in bar.QuxSource)
    {
        Foo item;
        ... //a procudure that is intricate enough not to be clearly repressentable with a LINQ method
        yield return item;
        ... //The aforementioned inticate proceduce continues. Possiblily yielding more items
    }
}

我的意思是后者显然很棒。 凭借延迟操作的荣耀,如果我只使用 Foobar(someBar).First(),它不必生成所有返回的项目。

我看到前者被大量使用,尤其是经验丰富的编码人员。 (我猜他们不了解现代 C# 中的列表推导)。 那么在某些情况下前一种模式是否更好呢? (仅查看​​库代码,以重用为目标) 我在想也许能够生产这些元素取决于某些外部资源,例如打开文件。 foreach 的用例是什么? 我猜是这样的

最佳答案

您的示例用例是正确的,但更一般地说,您可能希望采用前一种模式,如果:

  • 源使用稀缺资源,您需要保证枚举器将被处置(如果您要在后一种方法中开始枚举并在中间停止而不处置枚举器,它将保持打开状态)
  • 应尽快枚举来源
  • 您必须保证评估整个源代码

关于c# - IEnumerable 理解与返回集合类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9013461/

相关文章:

c# - 是否可以在 C# 中编写 Quake 的快速 InvSqrt() 函数?

python - 通过列表理解创建矩阵时的冗余变量

python - 将一个字典的键与另一个字典的键与值列表进行比较

c++ - 如何生成像列表理解这样的 vector

python - 将嵌套的 for 循环转换为列表 comp 并从结果列表中过滤完全平方数

c# - 将 Rich Cards 数据添加到我的 dotnet 应用程序会导致其崩溃

c# - 服务崩溃的异常代码是什么?

c# - 可选参数和继承

c# - 无法针对对象断言

python - 获取每个元素有 K 个选项的 N 项列表?