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

share|improve this question

70% accept rate
feedback

6 Answers

up vote 9 down vote accepted
string[] stringArray = (string[])arrayList.ToArray(typeof(string));
share|improve this answer
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" – Praveen Kumar Jan 19 at 11:13
1  
This is how to do it. Maybe your computers got annoyed with you not using Google?! – Killercam Jan 19 at 13:58
feedback
public static string[] Convert(this ArrayList items)
{
    return items == null
        ? null
        : items.Cast<object>()
            .Select(x => x == null ? null : x.ToString())
            .ToArray();
}
share|improve this answer
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 Jan 19 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 Jan 19 at 11:04
Anyone care to explain the downvote? my answer doesn't seem that bad to me... – Nuffin Jan 19 at 12:20
Dude! My fault. I actually thought this was good and hurridly pressed the wrong button! Now it's +1! – Killercam Jan 26 at 16:09
@Killercam: Thanks :D – Nuffin Jan 26 at 21:43
feedback

use .ToArray(Type)

string[] stringArray = (string[])arrayList.ToArray(typeof(string));
share|improve this answer
emm...do I wrote something wrong, to get downvote? :/ – Reniuz Jan 19 at 11:03
feedback

Try do that with ToArray() method.

ArrayList a= new ArrayList(); //your ArrayList object
var array=(String[])a.ToArray(typeof(string)); // your array!!!
share|improve this answer
feedback

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)

share|improve this answer
feedback

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 ) );
share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.