Mega Code Archive

 
Categories / C# / Collections Data Structure
 

Convert a collection of strings to a comma separated list

//http://facebooktoolkit.codeplex.com/ //http://facebooktoolkit.codeplex.com/license using System.Collections.Generic; using System.Text; namespace Facebook.Utility {     /// <summary>     /// Helper functions for string manipulation     /// </summary>     public static class StringHelper     {         /// <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>         public static string ConvertToCommaSeparated<T>(IList<T> collection)         {             // 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;             var sb = new StringBuilder(preAllocation);             int i = 0;             bool isString = typeof(T) == typeof(string);             foreach (T key in collection)             {                 if (isString)                 {                     sb.Append('\'');                 }                 sb.Append(key.ToString());                 if (isString)                 {                     sb.Append('\'');                 }                 if (i < collection.Count - 1)                     sb.Append(",");                 i++;             }             return sb.ToString();         }     } }