How to convert a list (long) to an array of strings? (Vb)

I want to convert List (of Long) to a string array.

Reason: This is a list of database identifiers, and I want the comma delimited string to be passed to the saved process.

I tried this:

Dim commaDelimitedList As String = String.Join(",", itemIDList.Cast(Of String)().ToArray)

but I'm obviously not using Cast correctly, as it throws an exception: System.InvalidCastException: It is not possible to cast an object of type "System.Int64" to type "System.String" ..

Is there a way to get Cast to work for this, or am I sticking with ConvertAll and the delegate function?

+5
source share
3 answers

If you can use LINQ, this will do what you want:

Dim commaDelimitedList  As String = String.Join(",", itemIDList.Select(Function(itemID) itemID.ToString()).ToArray())
+8
source

- LINQ, int ,  CLR 2.0 ConvertAll(), ...

string s =  String.Join(",",
              l1.ConvertAll<string>(delegate(int i) 
                 { return i.ToString(); }).ToArray()); 
+3

I realized that I can use ConvertAll with a lambda function so that everything is fine on one line, so I think this is my solution:

  Dim commaDelimitedList As String = _
String.Join(",", itemIDList.ConvertAll(New Converter(Of Long, String)(Function(i As Long) CStr(i))).ToArray)
+2
source

All Articles