TFMvdBroek
TFMvdBroek

Reputation: 19

Get all numbers within a range (12300 > 12400)

Trying to find a way to do actions on each number within a range in C#. Let's say 12300 to 12400.

Tried:

IEnumerable<int> numbers = Enumerable.Range(12300, 12400);

But that just gives me a list that is 12400 numbers long starting at 12300.

Upvotes: 1

Views: 126

Answers (2)

Theodor Zoulias
Theodor Zoulias

Reputation: 43474

You could also create your own range-producing method if you need something special, like defining the step.

public static IEnumerable<int> RangeFromTo(int from, int toExclusive, int step)
{
    for (int i = from; i < toExclusive; i += step) yield return i;
}

Usage example:

IEnumerable<int> numbers = RangeFromTo(12300, 12400, 1);
Console.WriteLine(String.Join(", ", numbers));

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460068

Well you need to do the math for the second parameter which is the count:

int startNumber = 12300;
int endNumber = 12400;
int count = endNumber - startNumber + 1; // +1 if you want to include the end
var range = Enumerable.Range(startNumber, count);

Upvotes: 6

Related Questions