60

Closed as exact duplicate of this question.

I have an array/list of elements. I want to convert it to a string, separated by a custom delimitator. For example:

[1,2,3,4,5] => "1,2,3,4,5"

What's the shortest/esiest way to do this in c#?

I have always done this by cycling the list and checking if the current element is not the last one before adding the separator.

for(int i=0; i<arr.Length; ++i)
{
    str += arr[i].ToString();
    if(i<arr.Length)
        str += ",";
}

Is there a LINQ function that can help me write less code?

0

2 Answers 2

163
String.Join(",", arr.Select(p=>p.ToString()).ToArray())
Sign up to request clarification or add additional context in comments.

2 Comments

You don't actually need the ToArray()... string.Join can take an IEnumerable, and IEnumerable.Select returns an IEnumerable.
@neminem string.Join(string, IEnumerable<string>) did not exist in 2008.
39
String.Join(",", array.Select(o => o.ToString()).ToArray());

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.