Using IEnumerable without foreach loop

You can get a reference to the Enumerator, using the GetEnumerator method, then you can use the MoveNext() method to move on, and use the Current property to access your elements: var enumerator = getInt().GetEnumerator(); while(enumerator.MoveNext()) { int n = enumerator.Current; Console.WriteLine(n); }

Implementing yield (yield return) using Scala continuations

Before we introduce continuations we need to build some infrastructure. Below is a trampoline that operates on Iteration objects. An iteration is a computation that can either Yield a new value or it can be Done. sealed trait Iteration[+R] case class Yield[+R](result: R, next: () => Iteration[R]) extends Iteration[R] case object Done extends Iteration[Nothing] def … Read more

When NOT to use yield (return) [duplicate]

What are the cases where use of yield will be limiting, unnecessary, get me into trouble, or otherwise should be avoided? It’s a good idea to think carefully about your use of “yield return” when dealing with recursively defined structures. For example, I often see this: public static IEnumerable<T> PreorderTraversal<T>(Tree<T> root) { if (root == … Read more

Return all enumerables with yield return at once; without looping through

It is something that F# supports with yield! for a whole collection vs yield for a single item. (That can be very useful in terms of tail recursion…) Unfortunately it’s not supported in C#. However, if you have several methods each returning an IEnumerable<ErrorInfo>, you can use Enumerable.Concat to make your code simpler: private static … Read more

yield return statement inside a using() { } block Disposes before executing

When you call GetAllAnimals it doesn’t actually execute any code until you enumerate the returned IEnumerable in a foreach loop. The dataContext is being disposed as soon as the wrapper method returns, before you enumerate the IEnumerable. The simplest solution would be to make the wrapper method an iterator as well, like this: public static … Read more

Proper use of ‘yield return’

I tend to use yield-return when I calculate the next item in the list (or even the next group of items). Using your Version 2, you must have the complete list before returning. By using yield-return, you really only need to have the next item before returning. Among other things, this helps spread the computational … Read more