Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert System.Array to string[]

I have a System.Array that I need to convert to string[]. Is there a better way to do this than just looping through the array, calling ToString on each element, and saving to a string[]? The problem is I don't necessarily know the type of the elements until runtime.

like image 214
KrisTrip Avatar asked Dec 28 '09 18:12

KrisTrip


2 Answers

How about using LINQ?

string[] foo = someObjectArray.OfType<object>().Select(o => o.ToString()).ToArray(); 
like image 149
Craig Stuntz Avatar answered Sep 28 '22 16:09

Craig Stuntz


Is it just Array? Or is it (for example) object[]? If so:

object[] arr = ... string[] strings = Array.ConvertAll<object, string>(arr, Convert.ToString); 

Note than any 1-d array of reference-types should be castable to object[] (even if it is actually, for example, Foo[]), but value-types (such as int[]) can't be. So you could try:

Array a = ... object[] arr = (object[]) a; string[] strings = Array.ConvertAll<object, string>(arr, Convert.ToString); 

But if it is something like int[], you'll have to loop manually.

like image 25
Marc Gravell Avatar answered Sep 28 '22 15:09

Marc Gravell