Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to write [0..100] in C#?

I'm trying to think of clever, clear, and simple ways to write code that describes the sequence of integers in a given range.

Here's an example:

IEnumerable<int> EnumerateIntegerRange(int from, int to)
{
    for (int i = from; i <= to; i++)
    {
        yield return i;
    }
}
like image 699
Jay Bazuzi Avatar asked Oct 11 '08 16:10

Jay Bazuzi


2 Answers

This is already in the framework: Enumerable.Range.

For other types, you might be interested in the range classes in my MiscUtil library.

like image 81
Jon Skeet Avatar answered Oct 02 '22 23:10

Jon Skeet


Alternately, a fluent interface from extension methods:

public static IEnumerable<int> To(this int start, int end)
{
    return start.To(end, i => i + 1);
}

public static IEnumerable<int> To(this int start, int end, Func<int, int> next)
{
    int current = start;
    while (current < end)
    {
        yield return current;
        current = next(current);
    }
}

used like:

1.To(100)
like image 25
Jay Bazuzi Avatar answered Oct 02 '22 22:10

Jay Bazuzi