In this article, we are going to learn how to create a comma-separated string from a list of strings in C#. 

To download the source code for this article, you can visit our GitHub repository.

Let’s dive in.

Using String.Join Method To Create a Comma-Separated String

In C#, we can use the inbuilt string.Join() method to create a comma-separated string from a list of strings.  This method has several overloads, which we will explore as we go on:

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!
Become a patron at Patreon!
var fruitList = new List<string>
{
    "apple",
    "orange",
    "pineapple",
    "grape",
    "coconut"
};

var fruits = string.Join(",", fruitList);

Console.WriteLine($"Fruits: {fruits}");

As you can see, we are converting the list of strings fruitList to a comma-separated string by using an overload of string.Join() that accepts two parameters:

Join(String, IEnumerable<String>)

The string parameter represents the separator between each member of the list, which in this case is a comma. While the second parameter is the list we are concatenating with the specified separator.

Furthermore, since we are working with a list we can conditionally pass values:

var filterFruit = string.Join(",", fruitList.Where(fruit => fruit.Contains("apple")));

Console.WriteLine($"Filtered Fruit: {filterFruit}");

Here, we are returning only fruits that contain the word “apple”. 

Returning Comma-Separated String From a Trimmed List

What if we wish to create a comma-separated string but only from the last three elements of our fruitList? Lets’ see how we can achieve this:

var trimmedFruits = string.Join(",", fruitList.ToArray(), 2, 3);

Console.WriteLine($"Trimmed Fruits: {trimedFruits}");

In this case, we are using an overload of string.Join() that accepts four parameters:

Join(String, String[], Int32, Int32)

The string as usual, represents the separator. The second parameter is the array of strings we wish to concatenate. This is the reason we are converting fruitList to an array. The third parameter is the index position we want to commence our concatenation from. Lastly, the fourth parameter represents the number of elements to return from the list.

So, since we specify that we want to start from the second index position and return 3 elements, we get:

Is this material useful to you? Consider subsribing and get "ASP.NET Core Web API Best Practices" eBook for FREE!

pineapple,grape,coconut

Conclusion

In this article, we have learned how to return a comma-separated string from a list of strings in C#. We’ve also seen how we can filter our results or return only a small portion of our collection as a comma-separated string.

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Become a patron at Patreon!