Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 902
Johann Gerell Avatar asked Sep 20 '11 08:09

Johann Gerell


People also ask

Can we convert IEnumerable to List C#?

In C#, an IEnumerable can be converted to a List through the following lines of code: IEnumerable enumerable = Enumerable. Range(1, 300); List asList = enumerable. ToList();

How do I create a comma separated string from a List of strings in C#?

The standard solution to convert a List<string> to a comma-separated string in C# is using the string. Join() method. It concatenates members of the specified collection using the specified delimiter between each item.

How do you join a List of strings with a comma?

In Java, we can use String. join(",", list) to join a List String with commas.

Does string implement IEnumerable?

In C#, all collections (eg lists, dictionaries, stacks, queues, etc) are enumerable because they implement the IEnumerable interface. So are strings. You can iterate over a string using a foreach block to get every character in the string.


1 Answers

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));      } } 
like image 93
Jaime Avatar answered Sep 24 '22 20:09

Jaime