14

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

1

2 Answers 2

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"
Sign up to request clarification or add additional context in comments.

4 Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.