【发布时间】:2012-02-14 01:00:40
【问题描述】:
如何在 C# 中将 ArrayList 转换为 string[]?
【问题讨论】:
标签: c# arrays string arraylist type-conversion
如何在 C# 中将 ArrayList 转换为 string[]?
【问题讨论】:
标签: c# arrays string arraylist type-conversion
string[] myArray = (string[])myarrayList.ToArray(typeof(string));
【讨论】:
string[] stringArray = (string[])arrayList.ToArray(typeof(string));
【讨论】:
一个简单的谷歌或 MSDN 上的搜索就可以完成。这里:
ArrayList myAL = new ArrayList();
// Add stuff to the ArrayList.
String[] myArr = (String[]) myAL.ToArray( typeof( string ) );
【讨论】:
尝试使用ToArray() 方法。
ArrayList a= new ArrayList(); //your ArrayList object
var array=(String[])a.ToArray(typeof(string)); // your array!!!
【讨论】:
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();
}
【讨论】:
using System.Linq;。我也错过了.Cast<object>() 电话。
您可以使用 ArrayList 对象的 CopyTo 方法。
假设我们有一个数组列表,它的元素是字符串类型。
strArrayList.CopyTo(strArray)
【讨论】:
另一种方式如下。
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);
【讨论】: