Beyond LINQ: Sequence Generation in C#

I'm taking a post off from the Paint Wars posts, but I think this one is worth it.

 

Many languages have nice syntactic sugar for creating a sequence of numbers. Usually, the syntax says something like:

The expression "1..5" expands to the list "1, 2, 3, 4, 5".

 

This syntax lets you do fun things like the below F# code:

for i in 1..5 do
    printfn "%d" i

 

Like a lot of syntactic sugar, this is simple but powerful. So, how can we get similar effects in C#? Hint:It's very simple with extension methods.

public static IEnumerable<int> Through(this int startValue, int endValue)
{
    int offset;
    if (startValue < endValue)
    {
        offset = 1;
    }
    else
    {
        offset = -1;
    }

    for (int i = startValue; i != endValue + offset; i += offset)
    {
        yield return i;
    }
}

 

Now, we can write code like this in C#:

foreach(var i in 1.Through(5))
{
    Console.WriteLine(i);
}

 

Sure, the syntax is not quite as nice as 1..5, but it is not too bad, either.

Don't forget to write extension methods on int, long, and all of the other numeric types to support this. Another obvious addition is an overload that takes an additional argument for "step" (eg. "1.Through(7, 2)" would produce produce the sequence "1, 3, 5, 7").

Published 12 February 2009 03:48 PM by cmarinos
Filed under: , ,

Comments

# Christopher Steen said on 13 February, 2009 07:40 AM

Link Listing - February 12, 2009

# Christopher Steen said on 13 February, 2009 07:41 AM

ASP.NET ASP.NET Wire Format for Model Binding to Arrays, Lists, Collections, Dictionaries [Via: Scott...

# tofi9 said on 05 May, 2009 06:51 AM

You can also use: Enumerable.Range(1, 5).

# cmarinos said on 14 May, 2009 03:21 PM

Thanks for the comment about Enumerable.Range(). I didn't realize this existed. I still like the fluent syntax of the .Through style, not to mention that Enumerable.Range() is a bit limited in it's capabilities.

Leave a Comment

(required) 
(required) 
(optional)
(required)