Given a List<int> how to create a comma separated string?
2 Answers
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"
4 Comments
Jay Sinha
+1, Nice! But why is the type parameter on method
join is not inferred?dtb
@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.
David Sykes
With this code I get an error "error CS0308: The non-generic method 'string.Join(string, string[])' cannot be used with type arguments"
dtb
@DavidSykes: The generic overload of String.Join was added in .NET Framework 4. Are you perhaps using an earlier version?
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.