I am new to c# and I am using String.Join to attempt to turn an array list into a string that is hash separated, such as "1#2#3#4". I can't seem to get the syntax working correctly.
Here's what I'm trying:
ArrayList aryTest = new ArrayList();
aryTest.Add("1");
aryTest.Add("2");
aryTest.Add("3");
string strTest = "";
strTest = string.Join("#", aryTest.ToArray(typeof(string)));
How about:
var list = new List<string>() { "1", "2", "3" };
var joined = string.Join("#", list);
An ArrayList is an "old" generation class, that does not implement the IEnumerable<T> interface that is needed for string.Join, and also is not an string[] or object[] array, which could be used in a call to string.Join.
You are better of using a List<string>, because then you will not have to do ToArray, to allocate a new array, just to create a string.
You need an extra cast:
strTest = string.Join("#", (string[])aryTest.ToArray(typeof(string)));
Alternatively, use just ToArray(), without any arguments:
strTest = string.Join("#", aryTest.ToArray());
The reason is that different overloads of Join are called:
strTest.ToArray(typeof(string)) ---> string.Join(string, params object[])
// ToArray(Type) returns Array, it is passed as _one object_,
// its ToString() is called, the results is "System.String[]"
(string[])strTest.ToArray(typeof(string)) ---> string.Join(string, params string[])
strTest.ToArray() ---> string.Join(string, IEnumerable<string>)
// ToArray() returns object[]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With