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
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.
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.
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 .
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()
)
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With