ToString function for Generic List

Below is the method to output Generic list of objects as string.

 

UPDATE: I’ve replaced my original function with the code suggested by James Curran (see his comment below).

 

    public static string ToString<T>(IEnumerable<T> messages, string sComment)
    {
        StringBuilder sRet = new StringBuilder(sComment);
        if (messages != null)
        {
            foreach (T msg in messages)
            {
                sRet.AppendLine(msg.ToString());
            }
        }
        return sRet.ToString();
    }

        /// <summary>

        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="messages"></param>
        /// <param name="separator"></param>
        /// <param name="sComment"></param>
        /// <returns></returns>
        /// See also http://www.codemeit.com/linq/c-array-delimited-tostring.html
        public static string ToString<T>(this IEnumerable<T> messages, string separator, string sComment)
        {
            if (messages == null)
                throw new ArgumentException("source can not be null.");
            StringBuilder sb = new StringBuilder(sComment);
            if (string.IsNullOrEmpty(separator))
            {
                separator = Environment.NewLine;
            }
            if (messages != null)
            {
                foreach (T msg in messages)
                {
                    if (msg != null)         
{
sb.Append(msg.ToString());
sb.Append(separator);
     }  }
            }
            string sRet = StringHelper.TrimEnd(sb.ToString(), separator);
            return sRet;
        }
 

Similar function implemented as an extension method described in post:

Separator Delimited ToString for Array, List, Dictionary, Generic IEnumerable

 

Advertisements