Kurkula
Kurkula

Reputation: 6762

Adding new items to string array

I am trying to add 2 new array items to existing string array. I achieved the result but I am sure this is not the right way to do .

How can I add items to a string array.

string[] sg = {"x", "y" };    
string[] newSg = {"z", "w"};

string[] updatedSg = new string[sg.Length+newSg.Length];
for (int i = 0; i < sg.Length; i++)
{
    updatedSg[i] = sg[i];
}
for (int i = 0; i < newSg.Length; i++)
{
    updatedSg[sg.Length+i] = newSg[i];
}

Upvotes: 1

Views: 200

Answers (4)

brakeroo
brakeroo

Reputation: 1447

Using CopyTo()

var updatedSg  = new string[sg.Length + newSg.Length];
sg.CopyTo(updatedSg, 0); 
sgNew.CopyTo(updatedSg, sg.Length);

As answered here https://stackoverflow.com/a/1547276/7070657

Or per somebody's suggestion:

var temp = x.Length;
Array.Resize(ref x, x.Length + y.Length); 
y.CopyTo(x, temp); // x and y instead of sg and sgNew

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

You can Concat two arrays into one by using Linq:

 string[] updatedSg = sg
   .Concat(newSg)
   .ToArray();

An alternative is using List<String> for updatedSg collection type instead of array:

 List<string> updatedSg = new List<string>(sg);

 updatedSg.AddRange(newSg);

If you insist on updating an existing array then in general case you can have:

 // imagine we don't know the actual size 
 string[] updatedSg = new string[0];

 // add sg.Length items to the array
 Array.Resize(ref updatedSg, sg.Length + updatedSg.Length);

 // copy the items
 for (int i = 0; i < sg.Length; ++i)
   updatedSg[updatedSg.Length - sg.Length + i - 1] = sg[i]; 

 // add updatedSg.Length items to the array
 Array.Resize(ref updatedSg, newSg.Length + updatedSg.Length);

 // copy the items 
 for (int i = 0; i < newSg.Length; ++i)
   updatedSg[updatedSg.Length - newSg.Length + i - 1] = newSg[i]; 

Upvotes: 4

Thalles Ribeiro
Thalles Ribeiro

Reputation: 1

If i have to add items to an array dynamically, i would use a List instead of an Array (Lists have an Add() method very useful). You could even convert it to an array at the end of the process (with ToArray() method). But you can also use methods like Concat() as mentioned above.

Upvotes: 0

nvoigt
nvoigt

Reputation: 77294

You cannot add items to an array. You can use another container type, like a List, or you can create a new array with more elements and copy the old elements over. But you cannot add elements to an array and you cannot remove elements from an array. The number of elements in an array is fixed.

Upvotes: 5

Related Questions