Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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

Version 1: Using yield return

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

public static IEnumerable<Product> GetAllProducts() {     using (AdventureWorksEntities db = new AdventureWorksEntities())     {         var products = from product in db.Product                        select product;          return products.ToList<Product>();     } } 
like image 568
senfo Avatar asked Jan 03 '09 22:01

senfo


People also ask

When should you use yield return?

You use a yield return statement to return each element one at a time. The sequence returned from an iterator method can be consumed by using a foreach statement or LINQ query. Each iteration of the foreach loop calls the iterator method.

How does yield return work?

yield return is used with enumerators. On each call of yield statement, control is returned to the caller but it ensures that the callee's state is maintained. Due to this, when the caller enumerates the next element, it continues execution in the callee method from statement immediately after the yield statement.

What can yield be used for?

Yield is a keyword in Python that is used to return from a function without destroying the states of its local variable and when the function is called, the execution starts from the last yield statement. Any function that contains a yield keyword is termed a generator. Hence, yield is what makes a generator.

What should the return type be for a method that uses yield return?

The yield return statement returns one element at a time. The return type of yield keyword is either IEnumerable or IEnumerator . The yield break statement is used to end the iteration. We can consume the iterator method that contains a yield return statement either by using foreach loop or LINQ query.


2 Answers

Populating a temporary list is like downloading the whole video, whereas using yield is like streaming that video.

like image 25
anar khalilov Avatar answered Sep 29 '22 06:09

anar khalilov


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

Using your Version 2, you must have the complete list before returning. By using yield-return, you really only need to have the next item before returning.

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.

Another case where yield-return is preferable is if the IEnumerable represents an infinite set. 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.

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

like image 168
abelenky Avatar answered Sep 29 '22 08:09

abelenky