Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comma "izing" a list of items

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)
like image 908
user21826 Avatar asked Dec 15 '08 14:12

user21826


People also ask

How do you convert a List to a comma separated string?

A List of string can be converted to a comma separated string using built in string. Join extension method. string. Join("," , list);

How do you convert a List to a comma separated string in python?

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].

How can I convert comma separated string into a List string C#?

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.


2 Answers

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)))
like image 153
Joel Coehoorn Avatar answered Sep 28 '22 12:09

Joel Coehoorn


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.

like image 41
Daniel Fortunov Avatar answered Sep 28 '22 13:09

Daniel Fortunov