Convert IList to array in C#
Asked Answered
R

4

19

I want to convert IList to array: Please see my code:

IList list = new ArrayList();
list.Add(1);
Array array = new Array[list.Count];
list.CopyTo(array, 0);

Why I get System.InvalidCastException : At least one element in the source array could not be cast down to the destination array type? How that can be resolved assuming I can not use ArrayList as type for list variable ?

Update 1: I use .NET 1.1. So I can not use Generics, Linq and so on. I just want to receive result for the most common case - integer was given as example, I need this code works for all types so I use Array here (maybe I am wrong about using Array but I need, once again, common case).

Recuperative answered 29/2, 2012 at 21:35 Comment(4)
ArrayList is obsolete. Use List<T> instead.Huckaback
Are you using .NET 2.0? If you aren't then this all becomes much simpler with the generic collections.Foothill
#269171Peart
What version of .NET? System.Linq adds a great function ToArray()Choleric
M
37

You're creating an array of Array values. 1 is an int, not an Array. You should have:

IList list = new ArrayList();
list.Add(1);
Array array = new int[list.Count];
list.CopyTo(array, 0);

or, ideally, don't use the non-generic types to start with... use List instead of ArrayList, IList<T> instead of IList etc.

EDIT: Note that the third line could easily be:

Array array = new object[list.Count];

instead.

Marga answered 29/2, 2012 at 21:38 Comment(3)
Nice catch! I was thinking that he was using a constructor on the Array object.Drida
@Jon What should I do if I do not know the type of elements in array? The integer was just example - I need more generic approach(without Generics)Recuperative
@MichaelZ: You could use object[] instead.Marga
F
24

You can use Cast and ToArray:

Array array = list.Cast<int>().ToArray();
Fradin answered 29/2, 2012 at 21:40 Comment(0)
A
4

I'm surprised that

 Array array = new Array[list.Count];

even compiles but it does not do what you want it to. Use

 object[] array = new object[list.Count];

And, standard remark: if you can use C#3 or later, avoid ArrayList as much as possible. You'll probably be happier with a List<int>

Acid answered 29/2, 2012 at 21:38 Comment(1)
It compiles because it's an array of arrays.Bathroom
S
4

probably the most compact solution is this:

Enumerable.Range(0, list.Count).Select(i => list[i]).ToArray();

Sahaptin answered 26/8, 2019 at 8:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.