Last Updated: February 25, 2016
·
1.001K
· lucidquiet

A Better Enumerable.Range

Personally, I don't enjoy this all that much: Enumerable.Range(0, GetTotalEmployees()), at least when compared to doing something more like this:

(0).To(TotalEmployees)
    .Where(a => a % 2 == 0)
    .ToList()

// Output:
// 0, 2, 4, ... , 6, 8... 2n

Simply by adding this extension somewhere:

public static IEnumerable<int> To(this int from, int to)
{
    for (int i = from; i < to; i++)
    {
        yield return i;
    }
}

Admittedly it could be made more robust

  1. Check that from is less than to.
  2. Add Optional parameter for step.
  3. Type parameterizing based on the Type of step or of the to parameter so that it can produce ints or doubles.

But for the most part this works well.