14

Given a List<int> how to create a comma separated string?

dtb
  • 198,715
  • 31
  • 379
  • 417
Blankman
  • 236,778
  • 296
  • 715
  • 1,125

2 Answers2

33

You can use String.Join:

List<int> myListOfInt = new List<int> { 1, 2, 3, 4 };

string result = string.Join<int>(", ", myListOfInt);

// result == "1, 2, 3, 4"
dtb
  • 198,715
  • 31
  • 379
  • 417
  • +1, Nice! But why is the type parameter on method `join` is not inferred? – Jay Sinha Jul 04 '10 at 20:02
  • @Jay Sinha: It is, but I wanted to make explicit that I'm using an overload of String.Join that has a type parameter. You can safely omit it. – dtb Jul 04 '10 at 20:18
  • With this code I get an error "error CS0308: The non-generic method 'string.Join(string, string[])' cannot be used with type arguments" – David Sykes Apr 02 '13 at 13:11
  • 2
    @DavidSykes: The generic overload of String.Join was added in .NET Framework 4. Are you perhaps using an earlier version? – dtb Apr 02 '13 at 13:18
0

If it's going to be a large string, you may want to consider using the StringBuilder class because it is less memory intensive. It doesn't allocate memory each time you append another string, which yields performance improvements.