Convert a collection of strings to a comma separated list. - CSharp System

CSharp examples for System:String Convert

Description

Convert a collection of strings to a comma separated list.

Demo Code


using System.Text;
using System.Collections.Generic;

public class Main{
        /// <summary>
        /// Convert a collection of strings to a comma separated list.
        /// </summary>
        /// <param name="collection">The collection to convert to a comma separated list.</param>
        /// <returns>comma separated string.</returns>
        internal static string ConvertToCommaSeparated(ICollection<string> collection) {
            /////from  w w  w  . java2s.  co  m
            /// assumed that the average string length is 10 and double the buffer multiplying by 2
            /// if this does not fit in your case, please change the values
            /// 
            int preAllocation = collection.Count * 10 * 2;
            StringBuilder sb = new StringBuilder(preAllocation);
            int i = 0;
            foreach (string key in collection) {
                sb.Append(key);
                if (i < collection.Count - 1)
                    sb.Append(",");

                i++;
            }
            return sb.ToString();
        }
}

Related Tutorials