How to convert string array to string with delimiter in C#

By FoxLearn 11/6/2024 9:32:51 AM   29
To convert a string array into a single string with a delimiter in C#, you can use the string.Join method.

This method takes a delimiter and an array of strings as parameters, and it returns a single string where each element of the array is separated by the specified delimiter.

If you want to convert an array of integers to a comma-separated string.

int[] arr = new int[5] {1,2,3,4,5};

You can write like this:

var result = string.Join(",", arr);

This uses the following overload of string.Join:

public static string Join<T>(string separator, IEnumerable<T> values);

For example:

// Define an array of strings
string[] stringArray = { "apple", "banana", "cherry" };

// Convert the array to a single string with a delimiter (e.g., comma)
string result = string.Join(",", stringArray);
// Output
// apple,banana,cherry

The string.Join(",", stringArray) joins the elements of the stringArray with ", " as the delimiter.

You can replace ", " with any other delimiter, such as " - " or "; ".