M_Mogharrabi
M_Mogharrabi

Reputation: 1389

Convert List elements to String

What is the best way to convert list of Int32 to a string with a separator like ',' in C#?

Upvotes: 3

Views: 1045

Answers (4)

cuongle
cuongle

Reputation: 75306

You can use string.Join:

var intList = new[] { 1, 2, 3, 4, 5 };
var result = string.Join(",", intList);

Edit:

If you are from .NET 4.0, string.Join accepts input parameter as IEnumerable<T>, so you don't need to convert to Array by ToArray.

But if you are in .NET 3.5: like other answers, ToArray should be used.

Upvotes: 7

Lewis Harvey
Lewis Harvey

Reputation: 332

Join on a string: String.Join(",", list.ToArray());

Upvotes: 3

CloudyMarble
CloudyMarble

Reputation: 37566

string commaSeparated = String.Join(",", Intlist.ToArray());

Upvotes: 2

bAN
bAN

Reputation: 13825

string Result = string.Join(",", MyList.ToArray());

Upvotes: 3

Related Questions