Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 729
Nathan Osman Avatar asked Dec 23 '10 04:12

Nathan Osman


People also ask

Can we convert list to string in Java?

We use the toString() method of the list to convert the list into a string.

How do you convert a numeric array to a string in Python?

In Python an integer can be converted into a string using the built-in str() function. The str() function takes in any python data type and converts it into a string.


2 Answers

Use LINQ:

string[] the_array = the_list.Select(i => i.ToString()).ToArray(); 
like image 130
Etienne de Martel Avatar answered Sep 18 '22 14:09

Etienne de Martel


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.

like image 23
Cheeso Avatar answered Sep 20 '22 14:09

Cheeso