346

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"

5 Answers 5

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

This uses the following overload of string.Join:

public static string Join<T>(string separator, IEnumerable<T> values);
Sign up to request clarification or add additional context in comments.

4 Comments

You do not need to pass the explicit generic argument in this case. It will be inferred.
Pre .NET 4 string.Join(",", Array.ConvertAll(arr, i => i.ToString()))
Is there a simple way to do the reverse of this? Take the string and put it into an array?
@Kory: Using String.Split method, see msdn.microsoft.com/en-us/library/…
155

.NET 4

string.Join(",", arr)

.NET earlier

string.Join(",", Array.ConvertAll(arr, x => x.ToString()))

2 Comments

just realized i couldn't use the .net 4 version and i didn't understood why i was having an error until i saw your answer , thanks.
I am using .NET 4.5. I tried to concat the comma separated numbers with a string. I got an error saying "cannot convert string[] to char". So the earlier version worked flawlessly.
18
int[] arr = new int[5] {1,2,3,4,5};

You can use Linq for it

String arrTostr = arr.Select(a => a.ToString()).Aggregate((i, j) => i + "," + j);

Comments

7

You can have a pair of extension methods to make this task easier:

public static string ToDelimitedString<T>(this IEnumerable<T> lst, string separator = ", ")
{
    return lst.ToDelimitedString(p => p, separator);
}

public static string ToDelimitedString<S, T>(this IEnumerable<S> lst, Func<S, T> selector, 
                                             string separator = ", ")
{
    return string.Join(separator, lst.Select(selector));
}

So now just:

new int[] { 1, 2, 3, 4, 5 }.ToDelimitedString();

Comments

4

Use LINQ Aggregate method to convert array of integers to a comma separated string

var intArray = new []{1,2,3,4};
string concatedString = intArray.Aggregate((a, b) =>Convert.ToString(a) + "," +Convert.ToString( b));
Response.Write(concatedString);

output will be

1,2,3,4

This is one of the solution you can use if you have not .net 4 installed.

2 Comments

It performs poorly due to the string concatenation, though
yes it will perform poorly but before .net 4.0 String.join only take string array as parameter.Thus in that case we also need to convert in string .we can use ToString it perform better but there is problem of null exception

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.