Convert IList to array in C#

前端 未结 4 1958
后悔当初
后悔当初 2021-01-08 00:24

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


        
相关标签:
4条回答
  • 2021-01-08 00:55

    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>

    0 讨论(0)
  • 2021-01-08 00:58

    probably the most compact solution is this:

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

    0 讨论(0)
  • 2021-01-08 01:15

    You can use Cast and ToArray:

    Array array = list.Cast<int>().ToArray();
    
    0 讨论(0)
  • 2021-01-08 01:21

    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.

    0 讨论(0)
提交回复
热议问题