yield关键字是c#中一直困扰我的关键字之一,我从来都不确定自己是否正确地使用了它。

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

版本1:使用收益率

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>();
    }
}

当前回答

假设您的产品LINQ类使用类似的yield来枚举/迭代,第一个版本更有效,因为它每次迭代只产生一个值。

第二个例子是使用ToList()方法将枚举器/迭代器转换为列表。这意味着它手动遍历枚举器中的所有项,然后返回一个平面列表。

其他回答

考虑到确切的两个代码片段,我认为版本1更好,因为它可以更有效。假设有很多产品,调用者希望将其转换为dto。

var dtos = GetAllProducts().Select(ConvertToDto).ToList();

在版本2中,首先创建一个Product对象列表,然后创建另一个ProductDto对象列表。版本1没有Product对象的列表,只构建了所需的ProductDto对象的列表。

Even without converting, Version 2 has a problem in my opinion: The list is returned as IEnumerable. The caller of GetAllProducts() does not know how expensive the enumeration of the result is. And if the caller needs to iterate more than once, she will probably materialize once by using ToList() (tools like ReSharper also suggest this). Which results in an unnecessary copy of the list already created in GetAllProducts(). So if Version 2 should be used, the return type should be List and not IEnumerable.

这有点离题了,但由于这个问题被标记为最佳实践,我将继续发表我的意见。对于这种类型的东西,我非常喜欢把它变成一个属性:

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

            return products;
        }
    }
}

当然,它更像一个样板,但使用它的代码将看起来更干净:

prices = Whatever.AllProducts.Select (product => product.price);

vs

prices = Whatever.GetAllProducts().Select (product => product.price);

注意:我不会对任何可能需要一段时间才能完成工作的方法这样做。

收益率有两大用途

它有助于在不创建临时集合的情况下提供自定义迭代。(加载所有数据并循环)

它有助于进行有状态迭代。(流)

下面是一个简单的视频,我已经创建了完整的演示,以支持上述两点

http://www.youtube.com/watch?v=4fju3xcm21M

这两段代码实际上在做两件不同的事情。第一个版本将根据需要拉成员。第二个版本将在您开始对其进行任何操作之前将所有结果加载到内存中。

这个问题没有对错之分。哪一种更可取取决于具体情况。例如,如果您必须在一定时间内完成查询,并且需要对结果执行一些半复杂的操作,那么第二个版本可能更可取。但是要注意大的结果集,特别是在以32位模式运行这段代码时。在使用这个方法时,我已经被OutOfMemory异常咬了好几次。

要记住的关键是:区别在于效率。因此,您可能应该使用任何使代码更简单的方法,并且只在分析之后更改它。

直接返回列表。好处:

这样就更清楚了 该列表是可重用的。(迭代器不是)不是真的,谢谢Jon

You should use the iterator (yield) from when you think you probably won't have to iterate all the way to the end of the list, or when it has no end. For example, the client calling is going to be searching for the first product that satisfies some predicate, you might consider using the iterator, although that's a contrived example, and there are probably better ways to accomplish it. Basically, if you know in advance that the whole list will need to be calculated, just do it up front. If you think that it won't, then consider using the iterator version.