Kurkula Kurkula - 1 month ago 7
C# Question

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];
}

Answer

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]; 
Comments