Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

yield return versus return select

Tags:

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?

like image 802
Jader Dias Avatar asked Sep 25 '09 19:09

Jader Dias


People also ask

What is a yield return?

The yield is the income the investment returns over time, typically expressed as a percentage, while the return is the amount that was gained or lost on an investment over time, usually expressed as a dollar value.

What is the difference between return and yield return C#?

In the iterator block, the yield keyword is used together with the return keyword to provide a value to the enumerator object. This is the value that is returned, for example, in each loop of a foreach statement. The yield keyword is also used with break to signal the end of iteration."

What is the use of yield return in C#?

You use a yield return statement to return each element one at a time. The sequence returned from an iterator method can be consumed by using a foreach statement or LINQ query. Each iteration of the foreach loop calls the iterator method.

What does yield break return?

It specifies that an iterator has come to an end. You can think of yield break as a return statement which does not return a value. For example, if you define a function as an iterator, the body of the function may look like this: for (int i = 0; i < 5; i++) { yield return i; } Console.


1 Answers

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.

like image 132
Jeffrey Hantin Avatar answered Oct 30 '22 12:10

Jeffrey Hantin