Building an integer sequence using the Range operator in LINQ C#
July 16, 2014 Leave a comment
Say you need a list of integers from 1 to 10. The traditional way is the following:
List<int> traditional = new List<int>(); for (int i = 1; i <= 10; i++) { traditional.Add(i); }
There’s a more concise way to achieve this with the static Range method which accepts two parameters. The first integer in the sequence and a count variable which defines the number of elements in the list. The step parameter is 1 by default and cannot be overridden:
IEnumerable<int> intRange = Enumerable.Range(1, 10); foreach (int i in intRange) { Console.WriteLine(i); }
This will print the integers from 1 to 10.
Say you need an integer list from 100 to 110 inclusive:
IEnumerable<int> intRange = Enumerable.Range(100, 11);
View the list of posts on LINQ here.