How can I convert ArrayList
into string[]
in C#?
7 Answers
string[] myArray = (string[])myarrayList.ToArray(typeof(string));
-
2i tried this.i am getting following error on this "At least one element in the source array could not be cast down to the destination array type"Praveen Kumar– Praveen Kumar01/19/2012 11:13:59Commented Jan 19, 2012 at 11:13
-
1I know this is very late, but the reason you are getting that error is because the you probably have an ArrayList with elements that aren't strings too, and you are trying to cast the elements to string, which doesn't make any senseEames– Eames04/16/2017 08:52:10Commented Apr 16, 2017 at 8:52
use .ToArray(Type)
string[] stringArray = (string[])arrayList.ToArray(typeof(string));
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 ) );
Try do that with ToArray()
method.
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();
}
-
i tried this.but i am getting following error Error 'System.Collections.ArrayList' does not contain a definition for 'Select' and no extension method 'Select' accepting a first argument of type 'System.Collections.ArrayList' could be found (are you missing a using directive or an assembly reference?)Praveen Kumar– Praveen Kumar01/19/2012 11:03:19Commented Jan 19, 2012 at 11:03
-
You need to include
using System.Linq;
at the top of the file. Also I was missing a.Cast<object>()
call.Nuffin– Nuffin01/19/2012 11:04:14Commented Jan 19, 2012 at 11:04 -
Dude! My fault. I actually thought this was good and hurridly pressed the wrong button! Now it's +1!MoonKnight– MoonKnight01/26/2012 16:09:21Commented Jan 26, 2012 at 16:09
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)
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);