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>();
}
}
15 s
Populating a temporary list is like downloading the whole video, whereas using yield
is like streaming that video.