How to get a comma separated string from an array in C#?

0

 


In C#, you can easily convert an array of values into a comma-separated string by using the string.Join method. The string.Join method takes two parameters: the first parameter is the separator, in this case, a comma, and the second parameter is the array that you want to convert into a string.

Here's an example that demonstrates how to get a comma-separated string from an array in C#:


using System;

namespace ArrayToCommaSeparatedString
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] fruits = new string[] { "apple", "banana", "cherry", "date" };
            string commaSeparatedFruits = string.Join(", ", fruits);

            Console.WriteLine("Comma Separated Fruits: " + commaSeparatedFruits);
        }
    }
}


In this example, we created an array of string values named fruits and assigned some values to it.

Next, we used the string.Join method to convert the fruits array into a comma-separated string. The string.Join method takes two parameters: the first parameter is the separator, in this case, a comma, and the second parameter is the fruits array. The string.Join method returns a string that we stored in the commaSeparatedFruits variable.

Finally, we used the Console.WriteLine method to print the comma-separated string on the console. The output of the program will show the comma-separated string of the fruits array.

In conclusion, converting an array of values into a comma-separated string in C# is a simple and straightforward task that can be achieved by using the string.Join method. All you need to do is to pass the separator, in this case, a comma, and the array that you want to convert into a string, and the string.Join method will take care of the rest.

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !