Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting entire array of objects to string

I have an array of type object which are strings. I would like to convert them to strings. What would be the quickest way of doing so?

Eg.: I have this object[] and want to convert it so it is this string[].

UPDATE: I think the problem is that some of the objects on the object[] are actually other objects like integers. I would need to convert them to strings first. Please include that into your solution. Thanks.

like image 766
Diskdrive Avatar asked Aug 03 '10 08:08

Diskdrive


People also ask

How do you turn an array of objects into a string?

To convert a JavaScript array into a string, you can use the built-in Array method called toString . Keep in mind that the toString method can't be used on an array of objects because it will return [object Object] instead of the actual values.

Can you cast an Object array to a string array in java?

Java For Testers toArray() returns an Object[], it can be converted to String array by passing the String[] as parameter.


2 Answers

object[] data = new object[] { "hello", "world", "!" };

string[] stringData = data.Cast<string>().ToArray();

If your object array contains mixed elements you can use the ConvertAll method of Array:

object[] data = new object[] { "hello", 1, 2, "world", "!" };

string[] stringData = Array.ConvertAll<object, string>(data, o => o.ToString());
like image 81
Dirk Vollmar Avatar answered Sep 24 '22 23:09

Dirk Vollmar


string[] output = Array.ConvertAll(objects, item => item.ToString());
like image 30
Jaroslav Jandek Avatar answered Sep 20 '22 23:09

Jaroslav Jandek