Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an array populated with a range of values x through y

Tags:

arrays

c#

.net

Let's say I have integer variables x and y, and I want an array populated with values x through y. Is there a nice way to do this inline, using C#?

I know I can achieve this using an extension method:

public static int[] ExpandToArray(this int x, int y)
{
    var arr = int[y - x + 1];
    for (int i = x; i <= y; i++) 
    {
        arr[i-x] = i;
    }
    return arr;
}

And then use it to write:

x.ExpandToArray(y);

Is there a built-in way (without creating an extension method) in .NET to write something like x.ExpandToArray(y)?

like image 682
McGarnagle Avatar asked May 05 '12 19:05

McGarnagle


People also ask

How do you declare a range in an array?

Steps to Add a Range into an Array in VBA First, you need to declare a dynamic array using the variant data type. Next, you need to declare one more variable to store the count of the cells from the range and use that counter for the loop as well. After that, assign the range where you have value to the array.

How do you create a range of numbers in JavaScript?

the Array. map() function is used to create a new array with a modified range of numbers. the Math. floor() function rounds a number down to the nearest integer, it's used in the last example to ensure a whole number is passed to the Array() function regardless of the step size.


1 Answers

int[] numbers = Enumerable.Range(x, y - x + 1).ToArray();

Parameter #1 is start value. Parameter #2 is count.

like image 198
SimpleVar Avatar answered Oct 15 '22 01:10

SimpleVar