简体   繁体   English

如何转换List <int> 字符串[]?

[英]How to convert List<int> to string[]?

I need an easy way to convert a List<int> to a string array. 我需要一种简单的方法将List<int>转换为string数组。

I have: 我有:

var the_list = new List<int>();
the_list.Add(1);
the_list.Add(2);
the_list.Add(3);

string[] the_array = new string[the_list.Count];
for(var i = 0 ; i < the_array.Count; ++i)
    the_array[i] = the_list[i].ToString();

...which looks to be very ugly to me. ......对我来说这看起来很难看。

Is there an easier way? 有没有更简单的方法?


Note: I'm looking for an easier way - not necessarily a faster way. 注意:我正在寻找一种更简单的方法 - 不一定是更快的方式。

使用LINQ:

string[] the_array = the_list.Select(i => i.ToString()).ToArray();

Sorry, I don't have .NET installed on this machine, so totally untested: 对不起,我没有在这台机器上安装.NET,所以完全未经测试:

var theList = new List<int>() { 1, 2, 3 };

var theArray = theList.Select(e => e.ToString()).ToArray();       // Lambda Form
var theArray = (from e in theList select e.ToString()).ToArray(); // Query Form

I know you have a good answer, but you don't need LINQ or Select. 我知道你有一个很好的答案,但你不需要LINQ或Select。 You can do it with a ConvertAll and an anonymous method. 您可以使用ConvertAll和匿名方法来完成。 Like this: 像这样:

var list = new List<int>();
....
var array = list.ConvertAll( x => x.ToString() ).ToArray(); 

Similar idea, but I think this is not linq. 类似的想法,但我认为这不是linq。 in case that matters. 万一重要。

List has a ToArray() method. List有一个ToArray()方法。 It will save you typing but probably won't be more efficient. 它可以节省您的打字,但可能效率不高。

Because your list only has a number, you can easily convert them to a string. 因为您的列表只有一个数字,所以您可以轻松地将它们转换为字符串。 Just create a loop and convert its members to the string. 只需创建一个循环并将其成员转换为字符串。

string[] the_array = new string[the_list.Count];
int i=0;
foreach(var item in the_list)
{
  the_array[i] = item.ToString();
  i++;
}

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

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