Coder Perfect

Adding to a C# array with values


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;

Here’s what I’m trying to achieve in C# for those who have used PHP:

$arr = array();
for ($i = 0; $i < 10; $i++) {
    $arr[] = $i;

Asked by Ross

Solution #1

This is a viable option –

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

You can also use Lists, which have the advantage of not requiring you to know the array size when creating the list.

List<int> termsList = new List<int>();
for (int runs = 0; runs < 400; runs++)

// You can convert it back to an array if you would like to
int[] terms = termsList.ToArray();

Edit: a) for loops on ListT> are around 2 times cheaper than foreach loops on ListT>; b) looping on array is about 2 times cheaper than looping on ListT>; c) looping on array using for is 5 times cheaper than looping on ListT> using foreach (which most of us do).

Answered by Tamas Czinege

Solution #2

Using Linq’s technique This is made simple with Concat.

int[] array = new int[] { 3, 4 };

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

result 3,4,2

Answered by Yitzhak Weinberg

Solution #3

You can do that with a one-liner if you’re coding in C# 3:

int[] terms = Enumerable.Range(0, 400).ToArray();

This code sample implies you have a System utilizing directive. Put a LINQ at the top of your document.

Instead of an int[], you might want to use a List if you want something that can be dynamically resized, as it appears to be the case for PHP (I’ve never actually mastered it). This is how that code might look:

List<int> terms = Enumerable.Range(0, 400).ToList();

However, putting terms[400] to a value will not automatically create a 401st element. Instead, you’d need to use Add(), which looks like this:


Answered by Amanda Mitchell

Solution #4

Here are instructions on how to do it with an array.

C#, on the other hand, provides a very useful feature called System. Collections include:

Although many of them use an array internally, collections are a more elegant alternative to using an array.

C#, for example, provides a List collection that is remarkably comparable to the PHP array.

using System.Collections.Generic;

// Create a List, and it can only contain integers.
List<int> list = new List<int>();

for (int i = 0; i < 400; i++)

Answered by FlySwat

Solution #5

By 2019, you’ll be able to utilize LinQ to Append and Prepend in just one line.

using System.Linq;

and then:

terms= terms.Append(21).ToArray();

Answered by Leandro Bardelli

Post is based on