Add new item in existing array in c#.net

How to add new item in existing string array in C#.net?

I need to preserve the existing data.


Solution 1:

I would use a List if you need a dynamically sized array:

List<string> ls = new List<string>();
ls.Add("Hello");

Solution 2:

That could be a solution;

Array.Resize(ref array, newsize);
array[newsize - 1] = "newvalue"

But for dynamic sized array I would prefer list too.

Solution 3:

Using LINQ:

arr = (arr ?? Enumerable.Empty<string>()).Concat(new[] { newitem }).ToArray();

I like using this as it is a one-liner and very convenient to embed in a switch statement, a simple if-statement, or pass as argument.

EDIT:

Some people don't like new[] { newitem } because it creates a small, one-item, temporary array. Here is a version using Enumerable.Repeat that does not require creating any object (at least not on the surface -- .NET iterators probably create a bunch of state machine objects under the table).

arr = (arr ?? Enumerable.Empty<string>()).Concat(Enumerable.Repeat(newitem,1)).ToArray();

And if you are sure that the array is never null to start with, you can simplify it to:

arr.Concat(Enumerable.Repeat(newitem,1)).ToArray();

Notice that if you want to add items to a an ordered collection, List is probably the data structure you want, not an array to start with.