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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8924869/
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-09 05:12:43  来源:igfitidea点击:

How to convert ArrayList into string array(string[]) in c#

c#arraysstringarraylisttype-conversion

提问by Praveen Kumar

How can I convert ArrayListinto string[]in C#?

如何在 C# 中转换ArrayListstring[]

采纳答案by Mustafa Ekici

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

回答by Nuffin

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

回答by Renatas M.

use .ToArray(Type)

使用.ToArray(Type)

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

回答by Chuck Norris

Try do that with ToArray()method.

尝试用ToArray()方法做到这一点。

ArrayList a= new ArrayList(); //your ArrayList object
var array=(String[])a.ToArray(typeof(string)); // your array!!!

回答by Rajkumar Vasan

You can use CopyTo method of ArrayList object.

您可以使用 ArrayList 对象的 CopyTo 方法。

Let's say that we have an arraylist, which has String Type as Elements.

假设我们有一个数组列表,它的元素是字符串类型。

strArrayList.CopyTo(strArray)

回答by MoonKnight

A simple Google or search on MSDN would have done it. Here:

一个简单的谷歌或 MSDN 上的搜索就可以完成。这里:

ArrayList myAL = new ArrayList(); 

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

回答by user746227

Another way is as follows.

另一种方式如下。

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