Skip to content

Instantly share code, notes, and snippets.

@atifaziz
Last active March 30, 2017 09:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atifaziz/ce69bbb3dd2b64ec5fbe9c224d218198 to your computer and use it in GitHub Desktop.
Save atifaziz/ce69bbb3dd2b64ec5fbe9c224d218198 to your computer and use it in GitHub Desktop.
Anonymous Iterators in C# 7, Almost

Anonymous Iterators in C# 7, Almost

If you squint hard enough, you can almost believe that C# 7 now has anonymous iterators that you can use smack in the middle of your LINQ comprehension to introduce some ah-hoc operator:

from seq in new[] {
    new Func<int, int, int, IEnumerable<int>>((start, stop, step) => { return Seq(); IEnumerable<int> Seq() {
        for (var i = start; i < stop; i += step)
            yield return i;
    }})
}
from x in seq(0, 3, 1)
from y in seq(x, x + 5, 2)
select new { x, y }

Try it in C# Interactive 2.0 to see it in action:

Microsoft (R) Visual C# Interactive Compiler version 2.0.0.61501
Copyright (C) Microsoft Corporation. All rights reserved.

Type "#help" for more information.
> from seq in new[] {
.     new Func<int, int, int, IEnumerable<int>>((start, stop, step) => { return Seq(); IEnumerable<int> Seq() {
.         for (var i = start; i < stop; i += step)
.             yield return i;
.     }})
. }
. from x in seq(0, 3, 1)
. from y in seq(x, x + 5, 2)
. select new { x, y }
SelectManyIterator { \{ x = 0, y = 0 }, \{ x = 0, y = 2 }, \{ x = 0, y = 4 },
                     \{ x = 1, y = 1 }, \{ x = 1, y = 3 }, \{ x = 1, y = 5 },
                     \{ x = 2, y = 2 }, \{ x = 2, y = 4 }, \{ x = 2, y = 6 } }
>

The trick pulling this off is use of a local function (which is really the new C# 7 addition at work here) inside a statement lambda.

Happy Hacking!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment