Creates a delimited string out of an IEnumerable list of T - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IEnumerable

Description

Creates a delimited string out of an IEnumerable list of T

Demo Code


using System.Text;
using System.Runtime.CompilerServices;
using System.Collections.Generic;
using System;//from  ww w .ja  v a  2s  .  c o m

public class Main{
        /// <summary>
        /// Creates a delimited string out of an IEnumerable list of T
        /// </summary>
        /// <typeparam name="T">Type contained in IEnumerable&lt;T&gt;</typeparam>
        /// <param name="list">IEnumerable list</param>
        /// <param name="delimiter">delimiter string, defaults to ", ".</param>
        /// <returns>delimited string of the items in the list.</returns>
        public static string GetDelimitedString<T>(IEnumerable<T> list, string delimiter)
        {
            if (list != null)
            {
                delimiter = IsNullOrEmpty(delimiter) ? ", " : delimiter;
                StringBuilder builder = new StringBuilder();
                foreach (T item in list)
                    builder.Append(item.ToString()).Append(delimiter);

                if (builder.Length > 2)
                    return builder.ToString(0, builder.Length - 2);
            }
            return string.Empty;
        }
        #endregion

        #region GetDelimitedString
        /// <summary>
        /// Creates a comma ", " delimited string out of an IEnumerable list of T
        /// </summary>
        /// <typeparam name="T">Type contained in IEnumerable&lt;T&gt;</typeparam>
        /// <param name="list">IEnumerable list</param>
        /// <returns>comma delimited string of the items in the list.</returns>
        public static string GetDelimitedString<T>(IEnumerable<T> list)
        {
            return GetDelimitedString<T>(list, null);
        }
}

Related Tutorials