Erwin's Blog

Developing with .NET

Creating a delimiter separated list from list of strings

When you have a list of strings like IList<string> of IEnumerable<string> and you want to convert it to for example a comma separated list you can easily do that with the String.Join method.

List<string> list = new List<string>() { "A" , "B", "C", "D", "E" };
            
string commaSeparated = String.Join(",", list.ToArray());

The output will be like this:

A,B,C,D,E
 

This is an easy and clean way to create a delimiter separeated list of strings.

Posted: Jun 24 2009, 10:15 AM by erwin21 | with 3 comment(s) |
Filed under: , ,

Comments

jalpesh vadgam said:

Nice code..

# June 24, 2009 5:32 AM

Stephen Harrison said:

You might also like to check out System.Configuration.CommaDelimitedStringCollection (and CommaDelimitedStringCollectionConverter)

var collection = new CommaDelimitedStringCollection();

collection.Add("A");

collection.Add("B");

Debug.WriteLine(collection.ToString());

gives: A,B

var converter = new CommaDelimitedStringCollectionConverter();

Debug.WriteLine(converter.ConvertToString(collection));

gives: A,B

You can also use ConvertFromString(string) to get a collection from a comma seperated string.

Although naturally it doesn't have the flexibility to use different separators as the String.Join method has and the collection Add() blows up if the string already contains a comma which might be useful.

# June 24, 2009 9:29 AM

Dave said:

Simple enough but now re consume it back to the array? A split won't work because we didn't propose an escape character for commas.

# June 24, 2009 12:56 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)