Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: sequence from min to max [duplicate]

Tags:

c#

.net

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?

like image 950
M. X Avatar asked Jun 07 '13 13:06

M. X


2 Answers

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!
}
like image 167
Marc Gravell Avatar answered Oct 09 '22 08:10

Marc Gravell


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.

like image 38
Ilya Ivanov Avatar answered Oct 09 '22 09:10

Ilya Ivanov