Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding values to a C# array

Tags:

arrays

c#

Probably a really simple one this - I'm starting out with C# and need to add values to an array, for example:

int[] terms;  for(int runs = 0; runs < 400; runs++) {     terms[] = runs; } 

For those who have used PHP, here's what I'm trying to do in C#:

$arr = array(); for ($i = 0; $i < 10; $i++) {     $arr[] = $i; } 
like image 794
Ross Avatar asked Oct 14 '08 21:10

Ross


People also ask

How do you add two numbers together?

When we add, we combine numbers together to find the total. When adding, always line up the addends, the two numbers being combined, one on top of each other according to their place values. Add the numbers in the ones column first, then the tens column, and finally the hundreds column, to get the sum, or the total.

How do I add numbers to my C Plus Plus?

sum = num1 + num2; After that it is displayed on screen using the cout object.


2 Answers

You can do this way -

int[] terms = new int[400]; for (int runs = 0; runs < 400; runs++) {     terms[runs] = value; } 

Alternatively, you can use Lists - the advantage with lists being, you don't need to know the array size when instantiating the list.

List<int> termsList = new List<int>(); for (int runs = 0; runs < 400; runs++) {     termsList.Add(value); }  // You can convert it back to an array if you would like to int[] terms = termsList.ToArray(); 

Edit: a) for loops on List<T> are a bit more than 2 times cheaper than foreach loops on List<T>, b) Looping on array is around 2 times cheaper than looping on List<T>, c) looping on array using for is 5 times cheaper than looping on List<T> using foreach (which most of us do).

like image 107
Tamas Czinege Avatar answered Oct 10 '22 11:10

Tamas Czinege


Using Linq's method Concat makes this simple

int[] array = new int[] { 3, 4 };  array = array.Concat(new int[] { 2 }).ToArray(); 

result 3,4,2

like image 26
Yitzhak Weinberg Avatar answered Oct 10 '22 10:10

Yitzhak Weinberg