Add new item into array

A very simple request, I was surprised how hard csharp implemented it. At first I thought it should be as easy as this:

string[] myList = {“1”, “2”, “3”};
string[] newList = myList.Add(“4”);

But it turns out Array doesn’t have an Add() method. OK, my stupid way, copying…

string[] newList = new string[myList.Length + 1];
Array.Copy(myList, newList, myList.Length);
newList[myList.Length] = “4”;

I feelvery shameful to write those code out. Re-try conversion to ArrayList, I feel much better when I figured out the ArrayList constructor and Initialize block.

ArrayList newArrayList = new ArrayList(myList) {“4”};
string[] newList = newArrayList.ToArray(typeof(string)) as string[];

And, how about using string join?

string[] myList = {“1”, “2”, “3”};
string[] newList = {string.Join(“,”, myList), “4”);

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s