Enumerable.Range can be used to create a sequence of numbers. By default it can create an IEnumerable<int> in the following way:

Enumerable.Range(0, 5) generates the following sequence: 0,1,2,3,4

Combining this functionality with a lambda expression you can generate any type of numbered list

doubles
Enumerable.Range(0,5).Select(n=>(double)n) generates the sequence 0.0,1.0,2.0,3.0,4.0

or an expression (function)
offset = 4.0
step =0.2
Enumerable.Range(0,5).Select(n=>offset n*step) yields 4.0, 4.2, 4.4, 4.6, 4.8

Enumerable.Repeat can be used to create a sequence of numbers that are all the same
Enumerable.Repeat(5, 3) yields 5, 5, 5

I guess when you first look at this code it can be quite puzzling and you might prefer to use the more common approach for readability. Please let me know what you think.

double [] mySequence = new double[5];
double offset = 4;
double step =0.2
for (int i=0;i<5;i++)
{
   mySequence[i]= offset + i * step;
}

see also http://visualstudiomagazine.com/articles/2009/04/01/make-your-code-clear.aspx http://stevenharman.net/blog/archive/2008/02/12/ruby-has-ranges-and-so-does-c.aspx

  • No labels

1 Comment

  1. Unknown User (don)

    Nice, we already use Enumerable.Repeat(...) but certainly have to learn some new tricks, I'm currently reading LINQ in Action.

    About Range, in F# you can write [1..100] (wink). See http://www.markhneedham.com/blog/2009/01/19/f-vs-c-vs-java-functional-collection-parameters/