Reputation: 90465
Which are the advantages/drawbacks of both approaches?
return items.Select(item => DoSomething(item));
versus
foreach(var item in items)
{
yield return DoSomething(item);
}
EDIT As they are MSIL roughly equivalent, which one you find more readable?
Upvotes: 27
Views: 12412
Reputation: 124696
In the slow-moving corporate world where I currently spend more time than I'd wish, yield return has the enormous advantage that it doesn't need that brand new .NET 3.5 Framework that won't be installed for at least another 2 years.
Upvotes: 14
Reputation: 617
Select only allows you to return one object for each item in your "items" collection.
Using an additional .Where(x => DoIReallyWantThis(x))
allows you to weed out unwanted items, but still only allows you to return one object per item.
If you want potentially more than one object per item, you can use .SelectMany
but it is easy to wind up with a single long line that is less than easy to read.
"yield return" has the potential to make your code more readable if you are looking through a complex data structure and picking out bits of information here and there. The best example of this that I have seen was where there were around a dozen separate conditions which would result in a returned object, and in each case the returned object was constructed differently.
Upvotes: 5
Reputation: 36494
The yield return
technique causes the C# compiler to generate an enumerator class "behind the scenes", while the Select
call uses a standard enumerator class parameterized with a delegate. In practice, there shouldn't be a whole lot of difference between the two, other than possibly an extra call frame in the Select
case, for the delegate.
For what it's worth, wrapping a lambda around DoSomething
is sort of pointless as well; just pass a delegate for it directly.
Upvotes: 20