Add new item into array

2008 July 25
by Frank Mao

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″);

No comments yet

Leave a Reply

Note: You can use basic XHTML in your comments. Your email address will never be published.

Subscribe to this comment feed via RSS