Comma “izing” a list of items

前端 未结 10 1687
我寻月下人不归
我寻月下人不归 2021-02-04 08:53

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

10条回答
  •  臣服心动
    2021-02-04 09:41

    Dim Result As String
    Dim Items As New List(Of String)
    Items.Add("Hello")
    Items.Add("World")
    
    Result = String.Join(",", Items.ToArray())
    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
    

提交回复
热议问题