如何在c#中将ArrayList转换为字符串数组(string[])
本文关键字:数组 string 字符串 中将 转换 ArrayList | 更新日期: 2023-09-27 18:20:51
如何在C#中将ArrayList
转换为string[]
?
string[] myArray = (string[])myarrayList.ToArray(typeof(string));
使用.ToArray(类型)
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();
}
您可以使用ArrayList对象的CopyTo方法。
假设我们有一个arraylist,它将字符串类型作为元素。
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);