Convert System.Array to string[]

2019-01-17 09:27发布

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.

5条回答
Juvenile、少年°
2楼-- · 2019-01-17 10:16

Simple and basic approach;

Array personNames = Array.CreateInstance(typeof (string), 3);
// or Array personNames = new string[3];
personNames.SetValue("Ally", 0);
personNames.SetValue("Eloise", 1);
personNames.SetValue("John", 2);

string[] names = (string[]) personNames; 
// or string[] names = personNames as string[]

foreach (string name in names)
    Console.WriteLine(name);

Or just an another approach: You can use personNames.ToArray too:

string[] names = (string[]) personNames.ToArray(typeof (string));
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-01-17 10:21

How about using LINQ?

string[] foo = someObjectArray.OfType<object>().Select(o => o.ToString()).ToArray();
查看更多
贪生不怕死
4楼-- · 2019-01-17 10:29

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.

查看更多
该账号已被封号
5楼-- · 2019-01-17 10:29

You can use Array.ConvertAll, like this:

string[] strp = Array.ConvertAll<int, string>(arr, Convert.ToString);
查看更多
祖国的老花朵
6楼-- · 2019-01-17 10:29

This can probably be compressed, but it gets around the limitation of not being able to use Cast<> or Linq Select on a System.Array type of object.

Type myType = MethodToGetMyEnumType();
Array enumValuesArray = Enum.GetValues(myType);
object[] objectValues new object[enumValuesArray.Length];
Array.Copy(enumValuesArray, objectValues, enumValuesArray.Length);

var correctTypeIEnumerable = objectValues.Select(x => Convert.ChangeType(x, t));
查看更多
登录 后发表回答