In this article, we are going to learn how to create a comma-separated string from a list of strings in C#.
Let’s dive in.
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:
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”.
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:
pineapple,grape,coconut
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.
HttpClient and RestSharp are HTTP Client libraries that we can use to consume APIs. Working…
Unit Testing is extremely important for creating robust software. It's very simple in principle but…
Have you ever needed to sort a list of items, but didn't want to use…
In ASP.NET Core dependency injection, we usually register injectable dependencies at the start of our…
In this article, we are going to learn more about ranges and indices in C#,…
Issue #128 of the Code Maze weekly. Check out what's new this week and enjoy…