Set/extend List length in c#

后端 未结 3 1241
广开言路
广开言路 2020-12-16 19:34

Given a List in c# is there a way to extend it (within its capacity) and set the new elements to null? I\'d like something that works like

相关标签:
3条回答
  • 2020-12-16 20:22

    Why do you want to do that ? The main advantage of a List is that it can grow as needed, so why do you want to add a number of null or default elements to it ?

    Isn't it better that you use an array in this case ?

    0 讨论(0)
  • 2020-12-16 20:30
    static IEnumerable<T> GetValues<T>(T value, int count) {
       for (int i = 0; i < count; ++i)
          yield return value;
    }
    
    list.AddRange(GetValues<object>(null, number_of_nulls_to_add));
    

    This will work with 2.0+

    0 讨论(0)
  • 2020-12-16 20:33

    The simplest way is probably by creating a temporary array:

    list.AddRange(new T[size - count]);
    

    Where size is the required new size, and count is the count of items in the list. However, for relatively large values of size - count, this can have bad performance, since it can cause the list to reallocate multiple times.(*) It also has the disadvantage of allocating an additional temporary array, which, depending on your requirements, may not be acceptable. You could mitigate both issues at the expense of more explicit code, by using the following methods:

    public static class CollectionsUtil
    {
        public static List<T> EnsureSize<T>(this List<T> list, int size)
        {
            return EnsureSize(list, size, default(T));
        }
    
        public static List<T> EnsureSize<T>(this List<T> list, int size, T value)
        {
            if (list == null) throw new ArgumentNullException("list");
            if (size < 0) throw new ArgumentOutOfRangeException("size");
    
            int count = list.Count;
            if (count < size)
            {
                int capacity = list.Capacity;
                if (capacity < size)
                    list.Capacity = Math.Max(size, capacity * 2);
    
                while (count < size)
                {
                    list.Add(value);
                    ++count;
                }
            }
    
            return list;
        }
    }
    

    The only C# 3.0 here is the use of the "this" modifier to make them extension methods. Remove the modifier and it will work in C# 2.0.

    Unfortunately, I never compared the performance of the two versions, so I don't know which one is better.

    Oh, and did you know you could resize an array by calling Array.Resize<T>? I didn't know that. :)

    Update:
    (*) Using list.AddRange(array) will not cause an enumerator to be used. Looking further through Reflector showed that the array will be casted to ICollection<T>, and the Count property will be used so that allocation is done only once.

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