25

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?

Jader Dias
  • 88,211
  • 155
  • 421
  • 625
  • 12
    Your second code fragment is the *implementation* of Select. (Assuming this is LINQ to Objects.) That's all Select does -- it runs a foreach loop, runs the delegate on each item, and yields the results. – Eric Lippert Sep 25 '09 at 20:56
  • yep. But there is still differences when typing the first and the second. 1st difference : number of LOCs, 2nd difference: readability, 3rd difference: when yield return is present in a method, some restrictions apply (ie: you can't put return select after yield return in the same method). – Jader Dias Sep 25 '09 at 21:08

3 Answers3

18

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
  • 35,734
  • 7
  • 75
  • 94
13

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
  • 122,218
  • 32
  • 205
  • 338
5

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
  • 617
  • 1
  • 7
  • 17