Thursday, 4 June 2015

A closer look -Enumerable.Range (System.Linq)

Enumerable.Range is a small static method in the  Enumerable class from System.Linq

The Enumerable.Range() method performs a very simple function, but it’s results can be used to drive much more complex LINQ expressions.  In it's simplest form it can be used to generate a sequence of consecutive integers. 

It accepts two int parameters, start and count, and constructs a sequence of count consecutive integers, starting at start:


  • Range(int start, int count)
  • Returns a sequence of int from start to (start + count – 1).


So, for example, the code snippet below will create an List<int> of the numbers from 1 to 10:
   1: var numbers = Enumerable.Range(1, 10).ToList();
   2: string nums= string.Join(",", numbers); 
  3: // result will be : "1,2,3,4,5,6,7,8,9,10"

Not just for numbers !

Or it can be used to  to generate a string containing the English alphabet
   1: IEnumerable<char> letters = Enumerable
   2:  .Range(0, 26)
   3:  .Select(x => (char)(x + 'a'));
   4: string alphabet = string.Join("", letters); 
   5: // result will be : "abcdefghijklmnopqrstuvwxyz"
Handy eh ?

Getting a bit more complicated now, if we wanted a list of the first 5 even numbers, we could start with the number of expected items and use the .Select() clause in conjunction with the mod operator to bring back only the even numbers :
   1: var evens = Enumerable.Range(0, 5).Select(n => n*2).ToList();
   2: string ans = string.Join(",", evens ); 
   3: // result will be : "0,2,4,6,8"
Alternatively , you can achieve the same result using the .Where() clause against the total results to filter it down:
   1: var another= Enumerable.Range(0, 10).Where(n => (n % 2) == 0).ToList();
   2: string ans = string.Join(",", another); 
   3: // result again will be : "0,2,4,6,8"
Or if you want to provide a min value, max value, and a number of steps, as demonstrated in this question on StackOverflow and answered by by John Skeet:

i.e. basically what was needed here was to return something like this :

0, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000

Were the min was 0 , the max 1000 , and he wanted to get there in 11 steps.
   1: int numberOfSteps = 11, max = 1000, min = 0;
   2: var example = Enumerable.Range(0, numberOfSteps)
.Select(i => min + (max - min) * ((double)i / (numberOfSteps - 1)));
   3: string ans = string.Join(",", example); 
   4: // result will be : "0,100,200,300,400,500,600,700,800,900,1000"

Conclusion

The Enumerable.Range() method performs a very simple function, but it’s results can be used to drive much more complex LINQ expressions.