0

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

2
  • 2
    This is a major reason why the collections classes exist. msdn.microsoft.com/en-us/library/ybcx56wz.aspx Commented Jul 14, 2014 at 19:42
  • Side note: consider adding information on why you actually trying to do that - could be even better way than using List<string>/ IEnumerable<string>... Commented Jul 14, 2014 at 19:54

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Concat seems to be exactly what I was looking for :)
2

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

2 Comments

In my usage, there will never be a $ in the string, but I realized this was poor form. The reason why I was not using List<string> is because I am manipulating cells in Excel, and ranges in the API I am using are returned as arrays.
You can do ToList() and ToArray() to convert between the two. Or create an array that's the new size, and use Array.Copy to move items (if that sounds like the way you'd want to go, I could edit it into my answer), or Concat like Selman22 answered.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.