.NET, C#, Tips

IEnumerable to Comma Delimited String

A few years ago I blogged about how to take a delimited string and convert it to a IEnumerable. ¬†Today we ran across the opposite of this in that we wanted to take a list and convert it to a delimited string. ¬† This can come in handy for a number of situations so it’s worth taking a look.

Given:

List<int> values = new List<int> {10, 20, 25};

In older versions of .NET (prior to 4.0 I believe) the easiest way was to do something like the following:

string newString = string.Join(",", values.ToArray());

However, starting in 4.0, the Join has some additional overloads that make this just crazy simple:

string newString = string.Join(",", values);

If you have a list of strings, there is still some benefit to converting this to an array. There is another overload of Join that allows you to be more selective in what you are converting.

Given a list of strings like the following:

List<string> strings = new List<string> {"a", "b", "c", "d", "e", "f"};

We can look at the last overload of; String.Join(delimiter, string[], startIndex, count)

This gives us a delimited string, starting at the element in the array at startIndex and going for the number of count.

string delimited = string.Join(",", strings.ToArray(), 2, 2);

will return “c,d”

I love how the framework provides these methods, often with multiple overloads to give us a lot of power with very little code. Enjoy!