Reputation: 1277
I have an ArrayList
, need to add the items of ArrayList into a List of string. I tried the following:
listString.AddRange(new List<string>((string[])this.arrayList.ToArray()))
But this gives an exception of
Unable to cast object of type 'System.Object[]' to type 'System.String[]'
Please note :; I can't use .Cast as I am working in framework 4.0
.
Upvotes: 2
Views: 6831
Reputation: 493
ArrayList arrayList = new ArrayList {"A","B","C" };
List<string> listString = new List<string>();
foreach (string item in arrayList)
{
listString.Add(item);
}
var data = listString;
Upvotes: 0
Reputation: 185
Try to understand below code : this code solve problem.
ArrayList myAL = new ArrayList();
myAL.Add( "The" );
myAL.Add( "quick" );
myAL.Add( "brown" );
myAL.Add( "fox" );
// Creates and initializes a new Queue.
Queue myQueue = new Queue();
myQueue.Enqueue( "jumped" );
myQueue.Enqueue( "over" );
// Displays the ArrayList and the Queue.
Console.WriteLine( "The ArrayList initially contains the following:" );
PrintValues( myAL, '\t' );
Console.WriteLine( "The Queue initially contains the following:" );
PrintValues( myQueue, '\t' );
// Copies the Queue elements to the end of the ArrayList.
myAL.AddRange( myQueue );
Upvotes: -4
Reputation: 44
You can try the below code as follows:
ArrayList al = new ArrayList();
List<string> lst = new List<string>();
foreach (string l in al)
{
lst.Add(l);
}
Upvotes: 3
Reputation: 879
It seems to me, the safest way:
listString.AddRange(arrayList.ToArray().Select(e => e.ToString()));
Upvotes: 1
Reputation: 3206
Use ToArray(typeof(string))
to create an Array and then cast it to a more specific array type string[]
before adding it to the variable of type List<string>
listString.AddRange((string[])this.arrayList.ToArray(typeof(string)));
Upvotes: 4
Reputation: 2233
LINQ to objects has a Cast method, which returns an IEnumerable of T where all the types have been cast (assuming the cast is valid) , so i'd suggest:
this.ArrayList.Cast<string>().ToList();
or, if your listString is already existing:
listString.AddRange(this.ArrayList.Cast<string>());
Upvotes: 2
Reputation: 29016
You have to convert each elements of the array list into a string to add them in a List of strings. Better option for doing this is like the following:
listString.AddRange(arrayList.ToArray().Select(x => x.ToString()).ToList());
Upvotes: 1