ckv
ckv

Reputation: 10830

What is the best way to create a Comma separated String from numbers in a short[] Array in C#?

I have a short[] Numbers;

Now I want to convert the numbers in the array into a string with each array value separated by a comma. How do I do this in C#?

short[] Numbers = {1, 2, 3, 4};

I want this as a string "1,2,3,4" to store in the database.

PS: I checked many questions in SO for the same topic but did not get exact match. Hence I am asking this one

Upvotes: 3

Views: 158

Answers (3)

JaredPar
JaredPar

Reputation: 754595

Try the following

string result = String.Join(",", Numbers);

Note: this won't work in 3.5 or earlier because String.Join lacks the necessary overloads. To use this API the code would need to change to

string result = String.Join(",", Numbers.Select(x => x.ToString()).ToArray());

Upvotes: 10

Anchit
Anchit

Reputation: 558

It can be done using LINQ -

string result = String.Join(",", Numbers.Select(p=>p.ToString()).ToArray());

EDIT -

string result = String.Join(",", Numbers);

As pointed out by Jean Hominal below, the Select and the ToArray can be removed due to the String.Join<T>(String, IEnumerable<T>) overload.

Upvotes: 4

String result = string.Join(",", Numbers);

Upvotes: 4

Related Questions