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