96

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?

Johann Gerell
  • 24,991
  • 10
  • 72
  • 122

6 Answers6

155
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));

    }
}
Jaime
  • 2,148
  • 1
  • 16
  • 19
57
string output = String.Join(",", yourEnumerable);

String.Join Method (String, IEnumerable

Concatenates the members of a constructed IEnumerable collection of type String, using the specified separator between each member.

Davide Piras
  • 43,984
  • 10
  • 98
  • 147
13
collection.Aggregate("", (str, obj) => str + obj.ToString() + ",");
Jan
  • 15,802
  • 5
  • 35
  • 59
  • This will add a superfluous comma at the end, but you could add `.TrimEnd(',')` to get rid of it. – Robin Jul 30 '18 at 07:54
  • 2
    Do this and you won't need to trim at the end `collection.Aggregate((str, obj) => str + "," + obj.ToString());` – Hoang Minh Aug 17 '18 at 17:08
  • 4
    Note this is a potential performance issue. The Enumerable.Aggregate method uses the plus symbol to concatenate strings. It is much slower than the String.Join method. – chviLadislav Apr 03 '19 at 11:43
  • 1
    string.join is cheaper and less code as chviLadislav mentioned – Mohamad Hammash Dec 12 '22 at 15:28
6

(a) Set up the IEnumerable:

// In this case we are using a list. You can also use an array etc..
List<string> items = new List<string>() { "WA01", "WA02", "WA03", "WA04", "WA01" };

(b) Join the IEnumerable Together into a string:

// Now let us join them all together:
string commaSeparatedString = String.Join(", ", items);

// This is the expected result: "WA01, WA02, WA03, WA04, WA01"

(c) For Debugging Purposes:

Console.WriteLine(commaSeparatedString);
Console.ReadLine();
Dale K
  • 25,246
  • 15
  • 42
  • 71
BenKoshy
  • 33,477
  • 14
  • 111
  • 80
4
IEnumerable<string> foo = 
var result = string.Join( ",", foo );
Wiktor Zychla
  • 47,367
  • 6
  • 74
  • 106
1

To join a large array of strings into a string, do not directly use +, rather use a StringBuilder to iterate one by one, or String.Join in one shot.

Dale K
  • 25,246
  • 15
  • 42
  • 71
unruledboy
  • 2,455
  • 2
  • 23
  • 30
  • OT: For concatenations of 3 operands the compiler will turn those operations to one call of the string.Append method taking 3 parameters. So with more than 3 operands, StringBuilder come in handy. – Johann Gerell Sep 22 '11 at 07:10