Convertir System.array a string []
-
21-09-2019 - |
Pregunta
Tengo un System.array que necesito para convertir a string []. ¿Hay una mejor manera de hacer esto que acaba de bucle a través de la matriz, llamando ToString en cada elemento, y guardar en una cadena []? El problema es que no sé necesariamente del tipo de los elementos hasta el tiempo de ejecución.
Solución
Cómo sobre el uso de LINQ?
string[] foo = someObjectArray.OfType<object>().Select(o => o.ToString()).ToArray();
Otros consejos
¿Es sólo Array
? ¿O se trata (por ejemplo) object[]
? Si es así:
object[] arr = ...
string[] strings = Array.ConvertAll<object, string>(arr, Convert.ToString);
Nota que cualquier matriz 1-d de referencia de tipo debe ser moldeable para object[]
(incluso si en realidad es, por ejemplo, Foo[]
), pero el valor de tipo (tales como int[]
) no se puede. Lo que podría intentar:
Array a = ...
object[] arr = (object[]) a;
string[] strings = Array.ConvertAll<object, string>(arr, Convert.ToString);
Pero si se trata de algo así como int[]
, que tendrá que bucle de forma manual.
Puede utilizar Array.ConvertAll
, como esto:
string[] strp = Array.ConvertAll<int, string>(arr, Convert.ToString);
Simple y enfoque básico;
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);
O simplemente un otro enfoque: Se puede utilizar personNames.ToArray
también:
string[] names = (string[]) personNames.ToArray(typeof (string));
Esto puede probablemente ser comprimido, pero se pone alrededor de la limitación de no poder utilizar moldeada <> o LINQ Selecto de un tipo de objeto System.array.
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));