Comma “izing” a list of items

前端 未结 10 1826
我寻月下人不归
我寻月下人不归 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: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
    {
    
        /// 
        /// Creates a string from the sequence by concatenating the result
        /// of the specified string selector function for each element.
        /// 
        public static string ToConcatenatedString(
            this IEnumerable source,
            Func stringSelector)
        {
            return EnumerableExtensions.ToConcatenatedString(source, stringSelector, String.Empty);
        }
    
        /// 
        /// Creates a string from the sequence by concatenating the result
        /// of the specified string selector function for each element.
        /// 
        /// The string which separates each concatenated item.
        public static string ToConcatenatedString(
            this IEnumerable source,
            Func 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();
        }
    }
    

提交回复
热议问题