It's a simple question; I am a newbie in C#, how can I perform the following
I have
int[] arr = new int[5] {1,2,3,4,5};
I want to convert it to one string
string => "1,2,3,4,5"
Use the join() Function to Convert a List to a Comma-Separated String in Python. The join() function combines the elements of an iterable and returns a string. We need to specify the character that will be used as the separator for the elements in the string.
How to get a comma separated string from an array in C#? We can get a comma-separated string from an array using String. Join() method. In the same way, we can get a comma-separated string from the integer array.
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.
The simplest way to convert an array to comma separated String is to create a StringBuilder, iterate through the array, and add each element of the array into StringBuilder after appending the comma.
var result = string.Join(",", arr);
This uses the following overload of string.Join
:
public static string Join<T>(string separator, IEnumerable<T> values);
.NET 4
string.Join(",", arr)
.NET earlier
string.Join(",", Array.ConvertAll(arr, x => x.ToString()))
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