Alex Rivera | Logout

yield return versus return select

Asked 2009-09-25T19:52:22.347
27

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?

Edit
Report

1 Answer

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.

answered 2009-09-25T20:08:44.530

Your Answer