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?

4

2 回答 2

21
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!
}
于 2013-06-07T13:19:41.713 回答
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.

于 2013-06-07T13:19:53.073 回答