Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert array of integers to comma-separated string

Tags:

arrays

string

c#

It's a simple question; I am a newbie in C#, how can I perform the following

  • I want to convert an array of integers to a comma-separated string.

I have

int[] arr = new int[5] {1,2,3,4,5}; 

I want to convert it to one string

string => "1,2,3,4,5" 
like image 932
Haim Evgi Avatar asked Jan 21 '11 07:01

Haim Evgi


People also ask

How do you convert a List of integers to a comma separated string?

Use the join() Function to Convert a List to a Comma-Separated String in Python. The join() function combines the elements of an iterable and returns a string. We need to specify the character that will be used as the separator for the elements in the string.

How do you get a comma separated string from an array in C?

How to get a comma separated string from an array in C#? We can get a comma-separated string from an array using String. Join() method. In the same way, we can get a comma-separated string from the integer array.

Which method returns the elements of an array in a string where each element is separated by a comma?

The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string.

How do you add comma separated values in a string array in Java?

The simplest way to convert an array to comma separated String is to create a StringBuilder, iterate through the array, and add each element of the array into StringBuilder after appending the comma.


2 Answers

var result = string.Join(",", arr); 

This uses the following overload of string.Join:

public static string Join<T>(string separator, IEnumerable<T> values); 
like image 165
Cheng Chen Avatar answered Nov 13 '22 14:11

Cheng Chen


.NET 4

string.Join(",", arr) 

.NET earlier

string.Join(",", Array.ConvertAll(arr, x => x.ToString())) 
like image 36
leppie Avatar answered Nov 13 '22 14:11

leppie