Reputation: 15
I am trying to create a string array from an existing string and a string array as follows
string[] oldArray = { "Hello", "World" };
string oldString = "test string";
string[] newArray = { oldArray, oldString };
This is, unfortunately, not going to work as written, so I have been trying to come up with a non-iterating method of filling the newArray
with the elements of the old. The only solution I have found is to join with an arbitrary character(s) and then split using the same.
string[] arr = {"AString", "BString", "CString" }; // Passed to function
...
string arrAsString = String.Join("$", arr) + "$" + DateTime.Today.ToString("M/dd");
return arrAsString.Split('$');
But this is much slower in my tests than a for
loop. Are there any better solutions?
Edit: In response to an answer below: The reason why I was not using List is because I am manipulating cells in Excel, and ranges in the API I am using are returned as arrays
Upvotes: 0
Views: 328
Reputation: 56536
The only solution I have found is to join with an arbitrary character(s) and then split using the same.
Please don't do it this way! For one, if any of your strings have a $
in them, you'll get unexpected results.
You should probably be using a List<string>
. It's much like a string[]
, but it has a variable size.
var myList = new List<string> { "Hello", "World" };
myList.Add("test string");
Upvotes: 2
Reputation: 101681
You can try using Concat
method:
string[] newArray = oldArray.Concat(new [] { oldString }).ToArray();
Or, use List<T>
instead if you don't want a fixed size collection.
Upvotes: 2