views:

351

answers:

3

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?

+6  A: 

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.

Jeffrey Hantin
What's going to be different from passing a delegate, as opposed to the lambda, in this case?
Lasse V. Karlsen
return items.Select(DoSomething);
Jader Dias
Ah, like that, didn't think of that.
Lasse V. Karlsen
+1  A: 

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.

Paul Williams
+5  A: 

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.

Joe
Cool answer. But .NET Framework 3.5 is being updated soon (4.0).
Jader Dias
".NET Framework 3.5 is being updated soon" - Not where I work :(
Joe