1

I have a list of ints called MyList. In javascript, when we call toString on an array of numbers, it converts it into a string with each number separated with commas; I'm looking to do the same with in C#.

I tried calling .ToString() to the list but it's returning the type of the list. I'm thinking of a loop that iterates over the list and add each element to a stringbuilder, along with the comma, and then .ToString() the stringbuilder.

Is that the best way to do it?

Thanks.

3 Answers 3

7

use string.Join:

string result = string.Join(",", MyList);
Sign up to request clarification or add additional context in comments.

Comments

2

You can use the String.Join method to "implode" the array with a separator.

e.g.:

String.Join(",", MyList);

Comments

2

try use this code :

 List<int> MyList = new List<int>();
            MyList.Add(1);
            MyList.Add(2);
            MyList.Add(3);
            MyList.Add(4);
            MyList.Add(5);
            MyList.Add(6);

            var m = string.Join(",", MyList);

            MessageBox.Show(m.ToString());

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.