Shortest method to convert an array to a string in c#/LINQ

C#LinqArrays

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

String.Join(",", arr.Select(p=>p.ToString()).ToArray())

Solution 2 - C#

String.Join(",", array.Select(o => o.ToString()).ToArray());

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLorisView Question on Stackoverflow
Solution 1 - C#mmxView Answer on Stackoverflow
Solution 2 - C#David SchmittView Answer on Stackoverflow