I want to convert a List (of Long) into a string array.
Reason: it's a list of database IDs开发者_StackOverflow and I want to make a comma delimited string to pass into a stored proc.
I tried this:
Dim commaDelimitedList As String = String.Join(",", itemIDList.Cast(Of String)().ToArray)
but I'm clearly not using the Cast correctly since it throws an exception: System.InvalidCastException: Unable to cast object of type 'System.Int64' to type 'System.String'..
Is there a way to get Cast working for this, or am I stuck with ConvertAll and a delegate function?
If you can use LINQ this will do what you want:
Dim commaDelimitedList As String = String.Join(",", itemIDList.Select(Function(itemID) itemID.ToString()).ToArray())
Can't cast - unless you can LINQ, you have to convert each int into a string so you have an array of strings CLR 2.0 has a ConvertAll() method that will do that...
string s = String.Join(",",
l1.ConvertAll<string>(delegate(int i)
{ return i.ToString(); }).ToArray());
I realised that I could use ConvertAll with a lambda function to keep it all nicely 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)
精彩评论