How to get comma-separated values from an array in C# [2 Ways]


C# Convert array to comma-separated string: Here in this article will learn how to get comma-separated values from an array of strings or integers in C#. Working with an array is a common task we all perform while developing any application.

For example, we have a list or array of strings containing  UserName, and we want to display all the user names with comma separated values. Here will demonstrate 2 ways to convert an array of strings to a comma separate string. 

The first way is simply by making a For Loop and the second way is by using the C# built-in method i.e string.join(). We will also perform a benchmark test and try to figure out between them which one is faster in converting an array to comma separated string. 

2 ways to convert array to comma-separated string C#

  1. Using For loop.
  2. Using String.Join() method

Let's first create an array variable with some values. 

string[] userName={"Satinder Singh", "David John","Andrea Ely","Pamela Franz","Amit S"}; 

Here we declared a string array and added some values i.e user name. Now we will convert these user names into comma-separated.

# Using For Loop to convert array to comma-separated string.

Here we make a for loop through an array, read its value, and append it to StringBuilder with delimiter i.e comma. In the end, using .ToString() we convert StringBuilder to a string variable containing all user names with commas separated.

Our code looks like as shown below:

public void GetCSV_ByForLoop(string[] userName) {

	StringBuilder sbUserName = new StringBuilder();

	foreach (var name in userName)
		sbUserName.Append(name).Append(", ");
	string allUserName = sbUserName.ToString();	

# Using C# Built-in String.Join() method

In C#, we have a built-in method string.join() which concatenates the value of a given array, with a separator provided between each value. 

Our final code looks like as shown below:-

Code to convert an array of strings to the comma-separated string:

string strAllUserNames = string.Join(", ", userName);

 Code to convert an array of integers to the comma-separated string:

int[] rollNumber = { 101, 102, 103, 104, 105, 106 };
string strRollNumber = string.Join(",", rollNumber); 

Other Resource:

  1. C# For Loop
  2. C# String.Join()

Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.

PS: If you found this content valuable and want to thank me? 👳 Buy Me a Coffee

Subscribe to our newsletter

Get the latest and greatest from Codepedia delivered straight to your inbox.

Post Comment

Your email address will not be published. Required fields are marked *