如何在C#中将ArrayList转换为字符串数组(string[])

24

如何在 C# 中将 ArrayList 转换为 string[]

7个回答

61
string[] myArray = (string[])myarrayList.ToArray(typeof(string));

2
我尝试了这个。但是我得到了以下错误提示:"源数组中至少有一个元素无法转换为目标数组类型"。 - Praveen Kumar
1
我知道现在已经很晚了,但你遇到这个错误的原因可能是你有一个ArrayList,其中包含不是字符串的元素,并且你试图将这些元素强制转换为字符串,这是没有意义的。 - Eames

4

使用 .ToArray(Type)

string[] stringArray = (string[])arrayList.ToArray(typeof(string));

3
一次简单的谷歌搜索或在MSDN上搜索就可以解决了。这里是:
ArrayList myAL = new ArrayList(); 

// Add stuff to the ArrayList.
String[] myArr = (String[]) myAL.ToArray( typeof( string ) );

2
using System.Linq;

public static string[] Convert(this ArrayList items)
{
    return items == null
        ? null
        : items.Cast<object>()
            .Select(x => x == null ? null : x.ToString())
            .ToArray();
}

我尝试了这个,但是我得到了以下错误:错误:“System.Collections.ArrayList”不包含“Select”的定义,也没有接受类型为“System.Collections.ArrayList”的第一个参数的扩展方法“Select”可以找到(您是否丢失了使用指令或程序集引用?) - Praveen Kumar
你需要在文件顶部包含 using System.Linq;。另外,我漏掉了一个 .Cast<object>() 的调用。 - Nuffin
兄弟!我的错。我本来以为这很好,匆忙按错了按钮!现在是+1! - MoonKnight

2
尝试使用 ToArray() 方法来实现这个操作。
ArrayList a= new ArrayList(); //your ArrayList object
var array=(String[])a.ToArray(typeof(string)); // your array!!!

1
你可以使用ArrayList对象的CopyTo方法。
假设我们有一个ArrayList,其中元素的类型为String。
strArrayList.CopyTo(strArray)

0

另一种方法如下。

System.Collections.ArrayList al = new System.Collections.ArrayList();
al.Add("1");
al.Add("2");
al.Add("3");
string[] asArr = new string[al.Count];
al.CopyTo(asArr);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接