views:

249

answers:

3

I have a list of integer values (List) and would like to generate a string of comma delimited values. That is all items in the list output to a single comma delimted list.

My thoughts... 1. pass the list to a method. 2. Use stringbuilder to iterate the list and append commas 3. Test the last character and if it's a comma, delete it.

What are your thoughts? Is this the best way?

How would my code change if I wanted to handle not only integers (my current plan) but strings, longs, doubles, bools, etc, etc. in the future? I guess make it accept a list of any type.

+4  A: 

It's amazing what the Framework already does for us.

List<int> myValues;
string csv = String.Join(",", myValues.Select(x => x.ToString()).ToArray());

For the general case:

IEnumerable<T> myList;
string csv = String.Join(",", myList.Select(x => x.ToString()).ToArray());

As you can see, it's effectively no different. Beware that you might need to actually wrap x.ToString() in quotes (i.e., "\"" + x.ToString() + "\"") in case x.ToString() contains commas.

For an interesting read on a slight variant of this: see Comma Quibbling on Eric Lippert's blog.

Jason
`String.Join` needs a `string[]` as a second argument, and won't accept `int[]`.
Pavel Minaev
@Pavel Minaev: Thanks.
Jason
+2  A: 

You can use String.Join.

String.Join(
  ",",
  Array.ConvertAll(
     list.ToArray(),
     element => element.ToString()
  )
);
João Angelo
No need to specify generic type parameters in call to `ConvertAll` here - both `int` and `string` will be inferred.
Pavel Minaev
Thanks for the tip.
João Angelo
Instead of doing `Array.ConvertAll(...' you can just do `list.ConvertAll(e=>e.ToString()).ToArray)`, just less typing.
David
+1  A: 

You can create an extension method that you can call on any IEnumerable:

public static string JoinStrings<T>(
    this IEnumerable<T> values, string separator)
{
    var stringValues = values.Select(item =>
        (item == null ? string.Empty : item.ToString()));
    return string.Join(separator, stringValues.ToArray());
}

Then you can just call the method on the original list:

string commaSeparated = myList.JoinStrings(", ");
Whatsit