C# – Convert IEnumerable to Comma Separated String

c++collectionsienumerablelinqstring

Say that for debugging purposes, I want to quickly get the contents of an IEnumerable into one-line string with each string item comma-separated. I can do it in a helper method with a foreach loop, but that's neither fun nor brief. Can Linq be used? Some other short-ish way?

Best Answer

using System;
using System.Collections.Generic;
using System.Linq;

class C
{
    public static void Main()
    {
        var a = new []{
            "First", "Second", "Third"
        };

        System.Console.Write(string.Join(",", a));

    }
}