C#: Joining an Array of Elements Into One Single String

If you need to convert an array to singe delimited string it is easy to do. Below is an example C# code to demonstrate how to join an array of integer values into a single delimited string:

using System;

namespace JoinArrayElements
{
	class MainClass
	{
		public static void Main (string[] args)
		{
			int[] numbers = new int[] { 1,2,3,4 };

			foreach (int num in numbers)
			{
				Console.WriteLine(num);
			}

			var strJoined = string.Join(",", Array.ConvertAll(numbers, Convert.ToString));

			Console.WriteLine ("Joined Integer Array as a Single String: {0}", strJoined);
		}
	}
}

I am using the string.Join() to join my array, the first parameter would be the delimiter character for this example I am using the comma “,”. Then the second parameter is the array that contains all the elements, but this parameter only takes an array of string. Okay we can fix this by converting the array of integers to an array of strings, by using the Array.ConvertAll() method and passing the array values to be converted and set the data type to convert to. (more…)

Shares