Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert an array list to hash separated string?

Tags:

c#

arraylist

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)));
like image 628
RAPT Avatar asked Dec 11 '22 23:12

RAPT


2 Answers

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.

like image 70
Alex Avatar answered Dec 29 '22 01:12

Alex


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[]
like image 25
AlexD Avatar answered Dec 29 '22 00:12

AlexD