Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring an array with incremental values - is there a shortcut?

Tags:

arrays

c#

wpf

This question is probably pretty stupid, but I'm new to C# and I'm not sure if there are any shortcuts to do this. I have a dynamic array for which the range will always be 1-n, with n being variable. Is there anyway to declare an array and have it hold incremental values without looping?

Think along the lines of my array holding values 1-50. I'd like to declare an array as such (logically): double[] myArray = new double[] {1-50} or, more generically for my purposes double[] myArray = new double[] {1-n}. I don't know what made me think of this, I just thought I'd ask.

I am going to bind this array (or list) to a combo box in WPF. I guess setting a combo-box the same way would also work if there's a shortcut for that.

Sorry for the dumb question. =)

like image 233
Yatrix Avatar asked Aug 29 '11 18:08

Yatrix


People also ask

How to initialize an array with variables?

You initialize an array variable by including an array literal in a New clause and specifying the initial values of the array. You can either specify the type or allow it to be inferred from the values in the array literal.

What is the best way to initialize an array in Visual basic?

In visual basic, Arrays can be initialized by creating an instance of an array with New keyword. By using the New keyword, we can declare and initialize an array at the same time based on our requirements.

How to initialize value in array?

int num[5] = {1, 1, 1, 1, 1}; This will initialize the num array with value 1 at all index. The array will be initialized to 0 in case we provide empty initializer list or just specify 0 in the initializer list. Designated Initializer: This initializer is used when we want to initialize a range with the same value.


2 Answers

int n = 50;
var doubleArray = Enumerable.Range(1, n).Select(x => (double)x).ToArray();

That will generate a sequence of integers from 1 to n (in this case 50) and then cast each one to a double and create an array from those results.

like image 72
dlev Avatar answered Oct 04 '22 20:10

dlev


You could use a List<T> which represents a dynamic array to which you could add elements.

like image 21
Darin Dimitrov Avatar answered Oct 04 '22 20:10

Darin Dimitrov