How to convert IEnumerable<string> to one comma separated string?

C#StringLinqCollectionsIenumerable

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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

	}
}

Solution 2 - C#

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.

Solution 3 - C#

collection.Aggregate("", (str, obj) => str + obj.ToString() + ",");

Solution 4 - C#

IEnumerable<string> foo = 
var result = string.Join( ",", foo );

Solution 5 - C#

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

Solution 6 - C#

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

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
QuestionJohann GerellView Question on Stackoverflow
Solution 1 - C#JaimeView Answer on Stackoverflow
Solution 2 - C#Davide PirasView Answer on Stackoverflow
Solution 3 - C#JanView Answer on Stackoverflow
Solution 4 - C#Wiktor ZychlaView Answer on Stackoverflow
Solution 5 - C#BenKoshyView Answer on Stackoverflow
Solution 6 - C#unruledboyView Answer on Stackoverflow