5

I want to get a sequence of integers from a value A to a value B.

For example A=3 and B=9. Now I want to create a sequence 3,4,5,6,7,8,9 with one line of code and without a loop. I played around with Enumerable.Range, but I find no solution that works.

Has anybody an idea?

M. X
  • 1,307
  • 4
  • 19
  • 34
  • 6
    Given that the answers are all likely to use Enumerable.Range, it would really have helped if you'd shown what you'd already tried, and said what happened. – Jon Skeet Jun 07 '13 at 13:20
  • 2
    @Marc & Ilya, That is a *lot* of easy points you guys just picked up. – Buh Buh Jun 07 '13 at 13:35

2 Answers2

22
var sequence = Enumerable.Range(min, max - min + 1);

?

For info, though - personally I'd still be tempted to use a loop:

for(int i = min; i <= max ; i++) { // note inclusive of both min and max
    // good old-fashioned honest loops; they still work! who knew!
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
16
int A = 3;
int B = 9;
var seq = Enumerable.Range(A, B - A + 1);

Console.WriteLine(string.Join(", ", seq)); //prints 3, 4, 5, 6, 7, 8, 9

if you have lots and lots of numbers and the nature of their processing is streaming (you handle items one at a time), then you don't need to hold all of the in memory via array and it's comfortable to work with them via IEnumerable<T> interface.

Ilya Ivanov
  • 23,148
  • 4
  • 64
  • 90