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)
or you can do:
By setting the separator to an empty string in the first iteration you skip the first comma. One less if statement. This might or might not be more readable depending on what you're used to
If you don't have to use
StringBuilder
orConcat
method you could also use:This requires a reference to System.Configuration
The idea is to use
String.TrimEnd() function
Does the solution have to use a
StringBuilder
or theConcat
method?If not, you could use the static
String.Join
method. For example (in C#):See my very similar question for more details on this.
Going on from the String.Join answer, to ignore null/empty strings (and if you are using .NET 3.5) you could use a bit of Linq. e.g.
Would you believe there's a class in the .NET framework which provides this functionality?