简体   繁体   中英

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

I need an easy way to convert a List<int> to a string array.

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:

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. You can do it with a ConvertAll and an anonymous method. Like this:

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

Similar idea, but I think this is not linq. in case that matters.

List has a ToArray() method. 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++;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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