What is the best way for String.Join for a non-string array?

What is the abbreviated path to String.Join a non-string array, as in the second example?

string[] names = { "Joe", "Roger", "John" };
Console.WriteLine("the names are {0}", String.Join(", ", names)); //ok

decimal[] prices = { 39.99M, 29.99m, 29.99m, 19.99m, 49.99m };
Console.WriteLine("the prices are {0}", String.Join(", ", prices)); //bad overload
+5
source share
5 answers

If you have LINQ:

decimal[] prices = { 39.99M, 29.99m, 29.99m, 19.99m, 49.99m }; 
Console.WriteLine("the prices are {0}", 
    String.Join(", ", 
       prices.Select(p => p.ToString()).ToArray()
    )
);
+13
source
Console.WriteLine("the prices are {0}", String.Join(", ", Array.ConvertAll(prices, p => p.ToString()));
+4
source

Delimit, .
, , , , StringBuilder , , .
/ .

TextWriter , 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();
}

, ,

decimal[] prices = { 39.99M, 29.99m, 29.99m, 19.99m, 49.99m }; 
Console.WriteLine("the prices are {0}", prices.Delimit(", "));

decimal[] prices = { 39.99M, 29.99m, 29.99m, 19.99m, 49.99m }; 
Console.Write("the prices are ")
prices.Delimit(System.Console.Out, ", ");
Console.WriteLine();
+2

Picking up where ck is , postpone it to the method to make it reusable:

public static class EnumerableExtensions {
  public static string Join<T>(this IEnumerable<T> self, string separator) { 
    if (self == null) throw new ArgumentNullException();
    if (separator == null) throw new ArgumentNullException("separator");
    return String.Join(separator, self.Select(e => e.ToString()).ToArray());
  }
}

Now usage is more readable:

Console.WriteLine("the prices are {0}", prices.Join(", "));
+1
source

You can use linq to translate to strings:

Console.WriteLine("the prices are {0}", String.Join(", ", prices.Select(p => p.ToString()).ToArray()));

or use Aggregate () instead of string.Join ()

Console.WriteLine("the prices are {0}",
    prices.Select(p => p.ToString()).
          .Aggregate((total, p) => total + ", " + p));

or even (with slightly different formatting)

Console.WriteLine(
    prices.Select(p => p.ToString()).
          .Aggregate("the prices are", (total, p) => total + ", " + p));
0
source

All Articles