yield return versus return select

Jader Dias picture Jader Dias · Sep 25, 2009 · Viewed 8.6k times · Source

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?

Answer

Jeffrey Hantin picture Jeffrey Hantin · Sep 25, 2009

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.