Comma “izing” a list of items

前端 未结 10 1684
我寻月下人不归
我寻月下人不归 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:32

    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.

    Dim Result As String
    Dim Items As New List(Of String)
    Items.Add("Hello")
    Items.Add("World")
    Result = String.Join(",", Items.ToArray().Where(Function(i) Not String.IsNullOrEmpty(i))
    MessageBox.Show(Result)
    
    0 讨论(0)
  • 2021-02-04 09:37

    Like this:

    lstItems.ToConcatenatedString(s => s, ", ")
    

    If you want to ignore empty strings as in your example:

    lstItems
        .Where(s => s.Length > 0)
        .ToConcatenatedString(s => s, ", ")
    

    The most popular custom aggregate function in my toolbox. I use it every day:

    public static class EnumerableExtensions
    {
    
        /// <summary>
        /// Creates a string from the sequence by concatenating the result
        /// of the specified string selector function for each element.
        /// </summary>
        public static string ToConcatenatedString<T>(
            this IEnumerable<T> source,
            Func<T, string> stringSelector)
        {
            return EnumerableExtensions.ToConcatenatedString(source, stringSelector, String.Empty);
        }
    
        /// <summary>
        /// Creates a string from the sequence by concatenating the result
        /// of the specified string selector function for each element.
        /// </summary>
        /// <param name="separator">The string which separates each concatenated item.</param>
        public static string ToConcatenatedString<T>(
            this IEnumerable<T> source,
            Func<T, string> stringSelector,
            string separator)
        {
            var b = new StringBuilder();
            bool needsSeparator = false; // don't use for first item
    
            foreach (var item in source)
            {
                if (needsSeparator)
                    b.Append(separator);
    
                b.Append(stringSelector(item));
                needsSeparator = true;
            }
    
            return b.ToString();
        }
    }
    
    0 讨论(0)
  • 2021-02-04 09:37

    or you can do:

    Separator = ""
    For Each Item In Collection
      Add Separator + Item To String
      Separator = ", "
    

    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

    0 讨论(0)
  • 2021-02-04 09:40

    Would you believe there's a class in the .NET framework which provides this functionality?

    public static string ListToCsv<T>(List<T> list)
            {
                CommaDelimitedStringCollection commaStr = new CommaDelimitedStringCollection();
    
                list.ForEach(delegate(T item)
                {
                    commaStr.Add(item.ToString());
                });
    
    
                return commaStr.ToString();
            }
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-02-04 09:41
    Dim strResult As String = ""
    Dim separator = ","
    Dim lstItems As New List(Of String)
    lstItems.Add("Hello")
    lstItems.Add("World")
    For Each strItem As String In lstItems
         strResult = String.Concat(strResult, separator)
    Next
    strResult = strResult.TrimEnd(separator.ToCharArray())
    MessageBox.Show(strResult)
    

    The idea is to use String.TrimEnd() function

    0 讨论(0)
提交回复
热议问题