Given a list of strings, what is the best method for concatenating these strings into a comma separated list with no comma at the end. (VB.NET or C#) (Using either StringBuilder or String Concat.)
Dim strResult As String = ""
Dim lstItems As New List(Of String)
lstItems.Add("Hello")
lstItems.Add("World")
For Each strItem As String In lstItems
If strResult.Length > 0 Then
strResult = strResult & ", "
End If
strResult = strResult & strItem
Next
MessageBox.Show(strResult)
A List of string can be converted to a comma separated string using built in string. Join extension method. string. Join("," , list);
How to Convert a Python List into a Comma-Separated String? You can use the . join string method to convert a list into a string. So again, the syntax is [seperator].
To convert a delimited string to a sequence of strings in C#, you can use the String. Split() method. Since the Split() method returns a string array, you can convert it into a List using the ToList() method.
Dim Result As String
Dim Items As New List(Of String)
Items.Add("Hello")
Items.Add("World")
Result = String.Join(",", Items)
MessageBox.Show(Result)
If you're really concerned about empty strings, use this join function:
Function Join(ByVal delimiter As String, ByVal items As IEnumerable(Of String), Optional ByVal IgnoreEmptyEntries As Boolean = True) As String
Dim delim As String = ""
Dim result As New Text.StringBuilder("")
For Each item As String In items
If Not IgnoreEmptyEntries OrElse Not String.IsNullOrEmpty(item) Then
result.Append(delim).Append(item)
delim = delimiter
End If
Next
Return result.ToString()
End Function
The above is really old. Today, I'd clear out empty strings like this:
Dim Result As String = String.Join("," Items.Where(Function(i) Not String.IsNullOrWhitespace(i)))
Does the solution have to use a StringBuilder
or the Concat
method?
If not, you could use the static String.Join
method. For example (in C#):
string result = String.Join(",", items.ToArray());
See my very similar question for more details on this.
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