I have two Delimit
functions that do this for me.
They've a very light footprint, in that no second array is created, and where a string is returned, a StringBuilder is used under the covers, so it's not copying and concatenating to the same string causing ever longer concatenation delays.
As such they are useful for series of very large and/or unknown length.
The frist writes to a TextWriter and returns nothing, the second returns a string, and delegates to the first passing in a StringWriter.
public static void Delimit<T>(this IEnumerable<T> me, System.IO.TextWriter writer, string delimiter)
{
var iter = me.GetEnumerator();
if (iter.MoveNext())
writer.Write(iter.Current.ToString());
while (iter.MoveNext())
{
writer.Write(delimiter);
writer.Write(iter.Current.ToString());
}
}
public static string Delimit<T>(this IEnumerable<T> me, string delimiter)
{
var writer = new System.IO.StringWriter();
me.Delimit(writer, delimiter);
return writer.ToString();
}
So given prices above you'd have
decimal[] prices = { 39.99M, 29.99m, 29.99m, 19.99m, 49.99m };
Console.WriteLine("the prices are {0}", prices.Delimit(", "));
or
decimal[] prices = { 39.99M, 29.99m, 29.99m, 19.99m, 49.99m };
Console.Write("the prices are ")
prices.Delimit(System.Console.Out, ", ");
Console.WriteLine();