How to initialize a List to a given size (as opposed to capacity)?

前端 未结 15 2166
礼貌的吻别
礼貌的吻别 2020-11-28 06:41

.NET offers a generic list container whose performance is almost identical (see Performance of Arrays vs. Lists question). However they are quite different in initialization

相关标签:
15条回答
  • 2020-11-28 07:05

    A notice about IList: MSDN IList Remarks: "IList implementations fall into three categories: read-only, fixed-size, and variable-size. (...). For the generic version of this interface, see System.Collections.Generic.IList<T>."

    IList<T> does NOT inherits from IList (but List<T> does implement both IList<T> and IList), but is always variable-size. Since .NET 4.5, we have also IReadOnlyList<T> but AFAIK, there is no fixed-size generic List which would be what you are looking for.

    0 讨论(0)
  • 2020-11-28 07:06

    If I understand correctly, you want the List<T> version of new T[size], without the overhead of adding values to it.

    If you are not afraid the implementation of List<T> will change dramatically in the future (and in this case I believe the probability is close to 0), you can use reflection:

        public static List<T> NewOfSize<T>(int size) {
            var list = new List<T>(size);
            var sizeField = list.GetType().GetField("_size",BindingFlags.Instance|BindingFlags.NonPublic);
            sizeField.SetValue(list, size);
            return list;
        }
    

    Note that this takes into account the default functionality of the underlying array to prefill with the default value of the item type. All int arrays will have values of 0 and all reference type arrays will have values of null. Also note that for a list of reference types, only the space for the pointer to each item is created.

    If you, for some reason, decide on not using reflection, I would have liked to offer an option of AddRange with a generator method, but underneath List<T> just calls Insert a zillion times, which doesn't serve.

    I would also like to point out that the Array class has a static method called ResizeArray, if you want to go the other way around and start from Array.

    To end, I really hate when I ask a question and everybody points out that it's the wrong question. Maybe it is, and thanks for the info, but I would still like an answer, because you have no idea why I am asking it. That being said, if you want to create a framework that has an optimal use of resources, List<T> is a pretty inefficient class for anything than holding and adding stuff to the end of a collection.

    0 讨论(0)
  • 2020-11-28 07:08

    Create an array with the number of items you want first and then convert the array in to a List.

    int[] fakeArray = new int[10];
    
    List<int> list = fakeArray.ToList();
    
    0 讨论(0)
提交回复
热议问题