C# 将 System.Array 转换为 string[]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1970738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:18:49  来源:igfitidea点击:

Convert System.Array to string[]

c#.netarrayssystem.array

提问by KrisTrip

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.

我有一个 System.Array,我需要将其转换为 string[]。有没有比循环遍历数组、在每个元素上调用 ToString 并保存到字符串 [] 更好的方法呢?问题是我在运行之前不一定知道元素的类型。

采纳答案by Craig Stuntz

How about using LINQ?

使用LINQ怎么样?

string[] foo = someObjectArray.OfType<object>().Select(o => o.ToString()).ToArray();

回答by Marc Gravell

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

只是Array吗?或者是(例如)object[]?如果是这样的话:

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:

请注意,任何引用类型的一维数组都应该可转换为object[](即使它实际上是,例如,Foo[]),但值类型(例如int[])不能。所以你可以试试:

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.

但如果是类似的int[],则必须手动循环。

回答by Amit Degadwala

You can use Array.ConvertAll, like this:

你可以使用Array.ConvertAll,像这样:

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

回答by bougiefever

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.

这可能可以压缩,但它绕过了无法在 System.Array 类型的对象上使用 Cast<> 或 Linq Select 的限制。

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));

回答by Umut D.

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.ToArraytoo:

或者只是另一种方法:您也可以使用personNames.ToArray

string[] names = (string[]) personNames.ToArray(typeof (string));