Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

What is a shorthand way 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
like image 468
Edward Tanguay Avatar asked Jul 06 '10 15:07

Edward Tanguay


People also ask

How do you join an array of strings?

join() The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

What is the most efficient way to concatenate many strings together?

When concatenating three dynamic string values or less, use traditional string concatenation. When concatenating more than three dynamic string values, use StringBuilder . When building a big string from several string literals, use either the @ string literal or the inline + operator.

How do you join an array to a string in Java?

To join elements of given string array strArray with a delimiter string delimiter , use String. join() method. Call String. join() method and pass the delimiter string delimiter followed by the string array strArray .


1 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()
    )
);
like image 125
cjk Avatar answered Nov 09 '22 12:11

cjk