c# - 正确使用 'yield return'

标签 c# yield-return

yield关键字是其中之一 keywords在 C# 中继续让我迷惑不解,而且我从来没有信心我正确地使用了它。

以下两段代码,哪一段是首选,为什么?

版本 1:使用 yield 返回

public static IEnumerable<Product> GetAllProducts()
{
    using (AdventureWorksEntities db = new AdventureWorksEntities())
    {
        var products = from product in db.Product
                       select product;

        foreach (Product product in products)
        {
            yield return product;
        }
    }
}

版本 2:返回列表

public static IEnumerable<Product> GetAllProducts()
{
    using (AdventureWorksEntities db = new AdventureWorksEntities())
    {
        var products = from product in db.Product
                       select product;

        return products.ToList<Product>();
    }
}

最佳答案

当我计算列表中的下一个项目(甚至下一组项目)时,我倾向于使用 yield-return。

使用您的第 2 版,您必须在返回之前拥有完整列表。 通过使用 yield-return,您实际上只需要在返回之前拥有下一个项目。

除其他外,这有助于将复杂计算的计算成本分摊到更大的时间范围内。例如,如果列表连接到 GUI 并且用户永远不会转到最后一页,则您永远不会计算列表中的最终项目。

另一种情况下,yield-return 更可取,如果 IEnumerable 表示无限集。考虑素数列表,或随机数的无限列表。您永远无法一次返回完整的 IEnumerable,因此您使用 yield-return 以递增方式返回列表。

在您的特定示例中,您有完整的产品列表,所以我会使用版本 2。

关于c# - 正确使用 'yield return',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/410026/

相关文章:

c# - yield return 语句如何不返回任何元素?

c# - 转换器显示枚举的描述,并在从 wpf 的组合框中选择项目时转换回枚举值

c# - 使用 GetType() 创建 List<T>

c# - 当迭代次数未知时创建嵌套 for 循环

c# - .NET 迭代器来包装抛出的 API

c# - 在完成返回后关闭 IDataReader

c# - 处理 ViewModels 和 CanExecute 处理程序

c# - DbContext.Find() 和 DbContext.SingleOrDefault() Entity Framework Core 之间的区别

c# - 在 yield return 函数中是否可以确保在同一个线程上调用终结器?

c# - 将值附加到现有 IEnumerable 的末尾时产生返回