694

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;
}
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
Ross
  • 46,186
  • 39
  • 120
  • 173
  • 11
    Shouldn't 'terms[] = value;' be 'terms[] = runs;'? – tymtam Feb 07 '13 at 01:28
  • In C#, you cannot change the array size once is created. If you want something like arrays but be able to add/remove elements, use List(). – Kamran Bigdely Jul 18 '19 at 17:17
  • @KamranBigdely not so true, you can use an array as IList<> and reassign the value with LinQ (using System.Linq): terms= terms.Append(21).ToArray(); – Leandro Bardelli Oct 16 '20 at 10:53
  • 1
    @Leandro: you are actually creating a new array every time you run it --> terms= terms.Append(21).ToArray(); – Kamran Bigdely Oct 19 '20 at 18:19
  • yes, and destroy in the assign, so what? – Leandro Bardelli Oct 20 '20 at 17:46
  • Here's the thing: what you're used to in PHP is not really an array, in the formal computer science sense. A _real_ array is a **fixed** block of **contiguous** memory. There are some nice optimizations you can do when you know you have a real array, but what PHP actually gives you is a **collection**. Now, C# also has collections like `List` (which is what you should use here), but when you ask C# for an array, it actually gives you a _real array_. – Joel Coehoorn Nov 04 '22 at 15:33

26 Answers26

1018

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).

Community
  • 1
  • 1
Tamas Czinege
  • 118,853
  • 40
  • 150
  • 176
  • 2
    Whats the advantage of using a list in this scenario? – Phill Healey Feb 17 '14 at 11:10
  • 17
    @PhillHealey You don't have to "know" how big the array might become, before you create it. As you can see, in these examples, OP has to put a value into "new int[400]" - but with the list, he doesn't have to do so. – Hejner Mar 05 '14 at 13:09
  • 1
    you need to be careful here as a list is just doing a dynamic array expansion under the covers would be good to at least know the capacity. – krystan honour Aug 05 '15 at 08:12
  • 3
    Wouldn't the first bit of code not be anything since value is not defined anywhere. -_- – EasyBB Sep 10 '15 at 03:47
  • Do C# List<>s have underlying contiguous memory or do they use linked elements? – Kapichu Jul 07 '17 at 20:50
  • 1
    Why you say that ARRAY need to have a size??? just do `new int[]{}` !!!!! – T.Todua Oct 08 '17 at 11:30
  • 1
    @Kapichu C# `List<>` is contiguous. The thing is that the underlying data structure of a `List<>` is nothing but an array and arrays are contiguous. You might want to read this - [.NET data structures: ArrayList, List, HashTable, Dictionary, SortedList, SortedDictionary — Speed, memory, and when to use each?](https://stackoverflow.com/q/128636/465053) – RBT Apr 25 '18 at 08:40
  • 14
    @T.Todua if you create an empty array like you are suggesting and then try to access it's non existent indexes to set values, you'll get an `OutOfRangeException` as soon as you run the code. Arrays need to be initialized with the size you are going to use, they reserve all the space at the beginning, witch makes them very fast, but not possible for them to be resized. – KinSlayerUY Sep 07 '18 at 14:25
  • by 2019 you can use terms= terms.Append(21).ToArray(); with using linQ – Leandro Bardelli Apr 02 '21 at 00:07
  • I would create a list and convert it to an Array. var listOfArray = llistOfData.ToArray(); – Shammie Apr 23 '21 at 10:42
149

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

John Cummings
  • 1,949
  • 3
  • 22
  • 38
Yitzhak Weinberg
  • 2,324
  • 1
  • 17
  • 21
  • 26
    The method will make adding 400 items to the array create a copy of the array with one more space and moving all elements to the new array, 400 hundred times. so is not recommended performance wise. – KinSlayerUY Sep 07 '18 at 14:28
  • Not entirely true @KinSlayerUY you can concat with the 400 elements at once. – wilmol Sep 21 '22 at 04:39
97

If you're writing in C# 3, you can do it with a one-liner:

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

This code snippet assumes that you have a using directive for System.Linq at the top of your file.

On the other hand, if you're looking for something that can be dynamically resized, as it appears is the case for PHP (I've never actually learned it), then you may want to use a List instead of an int[]. Here's what that code would look like:

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

Note, however, that you cannot simply add a 401st element by setting terms[400] to a value. You'd instead need to call Add() like this:

terms.Add(1337);
Leandro Bardelli
  • 10,561
  • 15
  • 79
  • 116
Amanda Mitchell
  • 2,665
  • 1
  • 16
  • 23
59

By 2019 you can use Append, Prepend using LinQ in just one line

using System.Linq;

and then in NET 6.0:

terms = terms.Append(21);

or versions lower than NET 6.0

terms = terms.Append(21).ToArray();
Leandro Bardelli
  • 10,561
  • 15
  • 79
  • 116
43

Answers on how to do it using an array are provided here.

However, C# has a very handy thing called System.Collections

Collections are fancy alternatives to using an array, though many of them use an array internally.

For example, C# has a collection called List that functions very similar 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++)
{
   list.Add(i);
}
Leandro Bardelli
  • 10,561
  • 15
  • 79
  • 116
FlySwat
  • 172,459
  • 74
  • 246
  • 311
14

Using a List as an intermediary is the easiest way, as others have described, but since your input is an array and you don't just want to keep the data in a List, I presume you might be concerned about performance.

The most efficient method is likely allocating a new array and then using Array.Copy or Array.CopyTo. This is not hard if you just want to add an item to the end of the list:

public static T[] Add<T>(this T[] target, T item)
{
    if (target == null)
    {
        //TODO: Return null or throw ArgumentNullException;
    }
    T[] result = new T[target.Length + 1];
    target.CopyTo(result, 0);
    result[target.Length] = item;
    return result;
}

I can also post code for an Insert extension method that takes a destination index as input, if desired. It's a little more complicated and uses the static method Array.Copy 1-2 times.

Karolis
  • 43
  • 1
  • 7
Thracx
  • 403
  • 5
  • 8
  • 3
    It would be much better, performance wise to create a list, fill it up and then do this copy to array at the end, so you are not creating and copying the array over and over 400 times – KinSlayerUY Sep 07 '18 at 14:30
  • Why do `T[] result = new T[target.Length + 1]; target.CopyTo(result, 0);` if you could just use [Array.Resize](https://learn.microsoft.com/en-us/dotnet/api/system.array.resize?view=net-7.0) instead? – EyesShriveledToRaisins Aug 21 '23 at 17:57
13

Based on the answer of Thracx (I don't have enough points to answer):

public static T[] Add<T>(this T[] target, params T[] items)
    {
        // Validate the parameters
        if (target == null) {
            target = new T[] { };
        }
        if (items== null) {
            items = new T[] { };
        }

        // Join the arrays
        T[] result = new T[target.Length + items.Length];
        target.CopyTo(result, 0);
        items.CopyTo(result, target.Length);
        return result;
    }

This allows to add more than just one item to the array, or just pass an array as a parameter to join two arrays.

Mark
  • 1,258
  • 13
  • 25
10

You have to allocate the array first:

int [] terms = new int[400]; // allocate an array of 400 ints
for(int runs = 0; runs < terms.Length; runs++) // Use Length property rather than the 400 magic number again
{
    terms[runs] = value;
}
Motti
  • 110,860
  • 49
  • 189
  • 262
7
int ArraySize = 400;

int[] terms = new int[ArraySize];


for(int runs = 0; runs < ArraySize; runs++)
{

    terms[runs] = runs;

}

That would be how I'd code it.

JB King
  • 11,860
  • 4
  • 38
  • 49
5

You can't just add an element to an array easily. You can set the element at a given position as fallen888 outlined, but I recommend to use a List<int> or a Collection<int> instead, and use ToArray() if you need it converted into an array.

AlexB
  • 7,302
  • 12
  • 56
  • 74
Michael Stum
  • 177,530
  • 117
  • 400
  • 535
5

C# arrays are fixed length and always indexed. Go with Motti's solution:

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

Note that this array is a dense array, a contiguous block of 400 bytes where you can drop things. If you want a dynamically sized array, use a List<int>.

List<int> terms = new List<int>();
for(int runs = 0; runs < 400; runs ++)
{
    terms.Add(runs);
}

Neither int[] nor List<int> is an associative array -- that would be a Dictionary<> in C#. Both arrays and lists are dense.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jimmy
  • 89,068
  • 17
  • 119
  • 137
5

If you really need an array the following is probly the simplest:

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++)
{
   list.Add(i);
}

int [] terms = list.ToArray();
Steve
  • 623
  • 4
  • 11
4

one approach is to fill an array via LINQ

if you want to fill an array with one element you can simply write

string[] arrayToBeFilled;
arrayToBeFilled= arrayToBeFilled.Append("str").ToArray();

furthermore, If you want to fill an array with multiple elements you can use the previous code in a loop

//the array you want to fill values in
string[] arrayToBeFilled;
//list of values that you want to fill inside an array
List<string> listToFill = new List<string> { "a1", "a2", "a3" };
//looping through list to start filling the array

foreach (string str in listToFill){
// here are the LINQ extensions
arrayToBeFilled= arrayToBeFilled.Append(str).ToArray();
}

Safi Habhab
  • 981
  • 10
  • 17
4

This seems like a lot less trouble to me:

var usageList = usageArray.ToList();
usageList.Add("newstuff");
usageArray = usageList.ToArray();
Phillip Holmes
  • 427
  • 4
  • 10
4

Array Push Example

public void ArrayPush<T>(ref T[] table, object value)
{
    Array.Resize(ref table, table.Length + 1); // Resizing the array for the cloned length (+-) (+1)
    table.SetValue(value, table.Length - 1); // Setting the value for the new element
}
Leandro Bardelli
  • 10,561
  • 15
  • 79
  • 116
Mondonno
  • 161
  • 1
  • 15
3
int[] terms = new int[10]; //create 10 empty index in array terms

//fill value = 400 for every index (run) in the array
//terms.Length is the total length of the array, it is equal to 10 in this case 
for (int run = 0; run < terms.Length; run++) 
{
    terms[run] = 400;
}

//print value from each of the index
for (int run = 0; run < terms.Length; run++)
{
    Console.WriteLine("Value in index {0}:\t{1}",run, terms[run]);
}

Console.ReadLine();

/*Output:

Value in index 0: 400
Value in index 1: 400
Value in index 2: 400
Value in index 3: 400
Value in index 4: 400
Value in index 5: 400
Value in index 6: 400
Value in index 7: 400
Value in index 8: 400
Value in index 9: 400
*/

vulcan raven
  • 32,612
  • 11
  • 57
  • 93
jhyap
  • 3,779
  • 6
  • 27
  • 47
3

If you don't know the size of the Array or already have an existing array that you are adding to. You can go about this in two ways. The first is using a generic List<T>: To do this you will want convert the array to a var termsList = terms.ToList(); and use the Add method. Then when done use the var terms = termsList.ToArray(); method to convert back to an array.

var terms = default(int[]);
var termsList = terms == null ? new List<int>() : terms.ToList();

for(var i = 0; i < 400; i++)
    termsList.Add(i);

terms = termsList.ToArray();

The second way is resizing the current array:

var terms = default(int[]);

for(var i = 0; i < 400; i++)
{
    if(terms == null)
        terms = new int[1];
    else    
        Array.Resize<int>(ref terms, terms.Length + 1);
    
    terms[terms.Length - 1] = i;
}

If you are using .NET 3.5 Array.Add(...);

Both of these will allow you to do it dynamically. If you will be adding lots of items then just use a List<T>. If it's just a couple of items then it will have better performance resizing the array. This is because you take more of a hit for creating the List<T> object.

Times in ticks:

3 items

Array Resize Time: 6

List Add Time: 16

400 items

Array Resize Time: 305

List Add Time: 20

Community
  • 1
  • 1
LCarter
  • 473
  • 7
  • 13
3

I will add this for a another variant. I prefer this type of functional coding lines more.

Enumerable.Range(0, 400).Select(x => x).ToArray();
David
  • 505
  • 3
  • 8
3

You can't do this directly. However, you can use Linq to do this:

List<int> termsLst=new List<int>();
for (int runs = 0; runs < 400; runs++)
{
    termsLst.Add(runs);
}
int[] terms = termsLst.ToArray();

If the array terms wasn't empty in the beginning, you can convert it to List first then do your stuf. Like:

    List<int> termsLst = terms.ToList();
    for (int runs = 0; runs < 400; runs++)
    {
        termsLst.Add(runs);
    }
    terms = termsLst.ToArray();

Note: don't miss adding 'using System.Linq;' at the begaining of the file.

Manar Gul
  • 289
  • 4
  • 7
2

Just a different approach:

int runs = 0; 
bool batting = true; 
string scorecard;

while (batting = runs < 400)
    scorecard += "!" + runs++;

return scorecard.Split("!");
Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
Ali Humayun
  • 1,756
  • 1
  • 15
  • 12
  • 3
    While slightly novel, this is performing a *lot* of string concatenation and then performing a large enumeration operation! Not the most performant, or easily understandable/readable way of going about this. – BradleyDotNET Sep 16 '14 at 23:47
  • @Ali Humayun did you really intend to use the assignment operator `=` instead of the comparison operator? You can leave out the battling variable and use `runs < 400` to control the loop. – Steve May 10 '15 at 03:10
  • just practicing programming double entendre – Ali Humayun May 11 '15 at 17:51
1
int[] terms = new int[400];

for(int runs = 0; runs < 400; runs++)
{
    terms[runs] = value;
}
Johnno Nolan
  • 29,228
  • 19
  • 111
  • 160
1
         static void Main(string[] args)
        {
            int[] arrayname = new int[5];/*arrayname is an array of 5 integer [5] mean in array [0],[1],[2],[3],[4],[5] because array starts with zero*/
            int i, j;


          /*initialize elements of array arrayname*/
            for (i = 0; i < 5; i++)
            {
                arrayname[i] = i + 100;
            }

             /*output each array element value*/
            for (j = 0; j < 5; j++)
            {
                Console.WriteLine("Element and output value [{0}]={1}",j,arrayname[j]);
            }
            Console.ReadKey();/*Obtains the next character or function key pressed by the user.
                                The pressed key is displayed in the console window.*/
        }
1
            /*arrayname is an array of 5 integer*/
            int[] arrayname = new int[5];
            int i, j;
            /*initialize elements of array arrayname*/
            for (i = 0; i < 5; i++)
            {
                arrayname[i] = i + 100;
            }
0

To add the list values to string array using C# without using ToArray() method

        List<string> list = new List<string>();
        list.Add("one");
        list.Add("two");
        list.Add("three");
        list.Add("four");
        list.Add("five");
        string[] values = new string[list.Count];//assigning the count for array
        for(int i=0;i<list.Count;i++)
        {
            values[i] = list[i].ToString();
        }

Output of the value array contains:

one

two

three

four

five

0

You can do this is with a list. here is how

List<string> info = new List<string>();
info.Add("finally worked");

and if you need to return this array do

return info.ToArray();
Leandro Bardelli
  • 10,561
  • 15
  • 79
  • 116
jerryurenaa
  • 3,863
  • 1
  • 27
  • 17
0

Here is one way how to deal with adding new numbers and strings to Array:

int[] ids = new int[10];
ids[0] = 1;
string[] names = new string[10];

do
{
    for (int i = 0; i < names.Length; i++)
    {
        Console.WriteLine("Enter Name");
        names[i] = Convert.ToString(Console.ReadLine());
        Console.WriteLine($"The Name is: {names[i]}");
        Console.WriteLine($"the index of name is: {i}");
        Console.WriteLine("Enter ID");
        ids[i] = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine($"The number is: {ids[i]}");
        Console.WriteLine($"the index is: {i}");
    }


} while (names.Length <= 10);
Leandro Bardelli
  • 10,561
  • 15
  • 79
  • 116