简体   繁体   English

C#中要数组的整数列表

[英]list of ints to array in c#

I have a list of ints called MyList . 我有一个称为MyList的整数列表。 In javascript, when we call toString on an array of numbers, it converts it into a string with each number separated with commas; 在javascript中,当我们在数字数组上调用toString时,它将其转换为一个字符串,每个数字都用逗号分隔; I'm looking to do the same with in C#. 我想在C#中做同样的事情。

I tried calling .ToString () to the list but it's returning the type of the list. 我尝试调用.ToString ()到列表,但是它返回列表的类型。 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. 我正在考虑一个循环遍历列表的循环,并将每个元素与逗号一起添加到stringbuilder中,然后将.ToString()添加到stringbuilder中。

Is that the best way to do it? 那是最好的方法吗?

Thanks. 谢谢。

使用string.Join

string result = string.Join(",", MyList);

You can use the String.Join method to "implode" the array with a separator. 您可以使用String.Join方法使用分隔符“插入”数组。

eg: 例如:

String.Join(",", MyList);

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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM