Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a comma separated list from IList<string> or IEnumerable<string>

Tags:

string

c#

What is the cleanest way to create a comma-separated list of string values from an IList<string> or IEnumerable<string>?

String.Join(...) operates on a string[] so can be cumbersome to work with when types such as IList<string> or IEnumerable<string> cannot easily be converted into a string array.

like image 698
Daniel Fortunov Avatar asked Apr 28 '09 19:04

Daniel Fortunov


People also ask

How to get comma-separated values in List of string in C#?

A List of string can be converted to a comma separated string using built in string. Join extension method. string. Join("," , list);


2 Answers

.NET 4+

IList<string> strings = new List<string>{"1","2","testing"}; string joined = string.Join(",", strings); 

Detail & Pre .Net 4.0 Solutions

IEnumerable<string> can be converted into a string array very easily with LINQ (.NET 3.5):

IEnumerable<string> strings = ...; string[] array = strings.ToArray(); 

It's easy enough to write the equivalent helper method if you need to:

public static T[] ToArray(IEnumerable<T> source) {     return new List<T>(source).ToArray(); } 

Then call it like this:

IEnumerable<string> strings = ...; string[] array = Helpers.ToArray(strings); 

You can then call string.Join. Of course, you don't have to use a helper method:

// C# 3 and .NET 3.5 way: string joined = string.Join(",", strings.ToArray()); // C# 2 and .NET 2.0 way: string joined = string.Join(",", new List<string>(strings).ToArray()); 

The latter is a bit of a mouthful though :)

This is likely to be the simplest way to do it, and quite performant as well - there are other questions about exactly what the performance is like, including (but not limited to) this one.

As of .NET 4.0, there are more overloads available in string.Join, so you can actually just write:

string joined = string.Join(",", strings); 

Much simpler :)

like image 92
Jon Skeet Avatar answered Oct 17 '22 06:10

Jon Skeet


FYI, the .NET 4.0 version of string.Join() has some extra overloads, that work with IEnumerable instead of just arrays, including one that can deal with any type T:

public static string Join(string separator, IEnumerable<string> values) public static string Join<T>(string separator, IEnumerable<T> values) 
like image 44
Xavier Poinas Avatar answered Oct 17 '22 07:10

Xavier Poinas