I've been posting a few extension methods here lately, so I thought I'd throw another into the mix. This set of ToConcatenatedString methods will take a list of objects and return a delimited string. It gives you the option of specifying your own delimiter (the default is ", ") and your own custom "toString" function if you want to do something other than call .ToString() on each object.

public static class ConcatenationExtensions { public static string ToConcatenatedString<T>(this IEnumerable<T> list,

string delimiter, Func<T, string> toString) { if (list == null || list.Count() == 0) return string.Empty; var sb = new StringBuilder(toString(list.First())); foreach (var t in list.Skip(1)) { sb.Append(delimiter); sb.Append(toString(t)); } return sb.ToString(); } public static string ToConcatenatedString<T>(this IEnumerable<T> list,

string delimiter) { return list.ToConcatenatedString(delimiter, t => t.ToString()); } public static string ToConcatenatedString<T>(this IEnumerable<T> list) { return list.ToConcatenatedString(", ", t => t.ToString()); } }

So now you can take, for example, a list of Customers, and say:

Console.WriteLine(custs.ToConcatenatedString("\n",

c => c.Name + " " + c.Address));

Handy for logging or quickly showing a message to the user.