Praveen Kumar
Praveen Kumar

Reputation: 1658

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

How can I convert ArrayList into string[] in C#?

Upvotes: 25

Views: 73699

Answers (7)

user746227
user746227

Reputation: 11

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

Upvotes: 0

Rajkumar Vasan
Rajkumar Vasan

Reputation: 712

You can use CopyTo method of ArrayList object.

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

strArrayList.CopyTo(strArray)

Upvotes: 1

Nuffin
Nuffin

Reputation: 3972

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

Upvotes: 2

Mustafa Ekici
Mustafa Ekici

Reputation: 7470

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

Upvotes: 63

Chuck Norris
Chuck Norris

Reputation: 15190

Try do that with ToArray() method.

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

Upvotes: 2

MoonKnight
MoonKnight

Reputation: 23833

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

ArrayList myAL = new ArrayList(); 

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

Upvotes: 3

Renatas M.
Renatas M.

Reputation: 11820

use .ToArray(Type)

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

Upvotes: 4

Related Questions