How to Get a Comma-Separated String from an Array in C#

Category > CSHARP || Published on : Tuesday, March 14, 2023 || Views: 170 || C# Arrays String.Join LINQ Comma-Separated String Programming


When working with arrays in C#, it's common to need to convert the values into a comma-separated string. This is especially useful when passing data between different layers of an application, or when displaying information to users. In this article, we'll look at how to get a comma-separated string from an array in C#.

When working with arrays in C#, it's common to need to convert the values into a comma-separated string. This is especially useful when passing data between different layers of an application, or when displaying information to users. In this article, we'll look at how to get a comma-separated string from an array in C#.

First, let's take a look at an example array:

string[] fruits = { "apple", "banana", "orange" };

To convert this array into a comma-separated string, we can use the string.Join method. This method takes two parameters: the separator to use between each value in the array, and the array itself. Here's an example:

string commaSeparatedFruits = string.Join(",", fruits);

In this example, we're using a comma as the separator. The resulting string will look like this:

"apple,banana,orange"

Note that the string.Join method can be used with any type of array, not just arrays of strings. For example, here's how to convert an array of integers into a comma-separated string:

int[] numbers = { 1, 2, 3 };
string commaSeparatedNumbers = string.Join(",", numbers);

The resulting string will look like this:

"1,2,3"

It's also worth noting that if you have a collection of objects that you want to convert into a comma-separated string, you can use LINQ to select the property you want to use as the value in the string. For example, if you have a collection of Person objects with a Name property, you could do the following:

List<Person> people = new List<Person>
{
    new Person { Name = "Alice" },
    new Person { Name = "Bob" },
    new Person { Name = "Charlie" }
};

string commaSeparatedNames = string.Join(",", people.Select(p => p.Name));

In this example, we're using LINQ to select the Name property of each Person object in the collection. The resulting string will look like this:

"Alice,Bob,Charlie"

In summary, to get a comma-separated string from an array in C#, use the string.Join method with the separator and array as parameters. This method can be used with any type of array, and you can use LINQ to select specific properties from a collection of objects.