How can I convert ArrayList into string[] in C#?
7 Answers
string[] myArray = (string[])myarrayList.ToArray(typeof(string));
2 Comments
Praveen Kumar
i 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"
Eames
I 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 sense
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();
}
3 Comments
Praveen Kumar
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?)
Nuffin
You need to include
using System.Linq; at the top of the file. Also I was missing a .Cast<object>() call.MoonKnight
Dude! My fault. I actually thought this was good and hurridly pressed the wrong button! Now it's +1!