Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

c# - 正确使用'收益率'(Proper use of 'yield return')

The yield keyword is one of those keywords in C# that continues to mystify me, and I've never been confident that I'm using it correctly.

(yield关键字是C#中那些继续使我神秘化的关键字之一,而且我从未确信我正确使用它。)

Of the following two pieces of code, which is the preferred and why?

(以下两段代码中,哪个是首选,为什么?)

Version 1: Using yield return

(版本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;
        }
    }
}

Version 2: Return the list

(版本2:返回列表)

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

        return products.ToList<Product>();
    }
}
  ask by senfo translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I tend to use yield-return when I calculate the next item in the list (or even the next group of items).

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

Using your Version 2, you must have the complete list before returning.

(使用版本2,您必须在返回之前拥有完整列表。)

By using yield-return, you really only need to have the next item before returning.

(通过使用yield-return,您实际上只需要在返回之前拥有下一个项目。)

Among other things, this helps spread the computational cost of complex calculations over a larger time-frame.

(除此之外,这有助于在更大的时间范围内分散复杂计算的计算成本。)

For example, if the list is hooked up to a GUI and the user never goes to the last page, you never calculate the final items in the list.

(例如,如果列表连接到GUI并且用户永远不会转到最后一页,则永远不会计算列表中的最终项目。)

Another case where yield-return is preferable is if the IEnumerable represents an infinite set.

(另一种情况,其中yield-return是优选的,如果IEnumerable表示无限集。)

Consider the list of Prime Numbers, or an infinite list of random numbers.

(考虑素数列表,或无限的随机数列表。)

You can never return the full IEnumerable at once, so you use yield-return to return the list incrementally.

(您永远不能一次返回完整的IEnumerable,因此您使用yield-return以递增方式返回列表。)

In your particular example, you have the full list of products, so I'd use Version 2.

(在您的特定示例中,您有完整的产品列表,因此我将使用版本2。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...