Convert IList to array in C#

大憨熊 提交于 2020-06-08 07:00:13

问题


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).


回答1:


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.




回答2:


You can use Cast and ToArray:

Array array = list.Cast<int>().ToArray();



回答3:


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>




回答4:


probably the most compact solution is this:

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



来源:https://stackoverflow.com/questions/9507002/convert-ilist-to-array-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!