Set/extend List<T> length in c# -


a list & lt; T & gt; Looking at C #, there is a way to expand it (within its capacity)) and set new element to null ? I need something that works like a memset . I'm not looking for sugar here, I need a fast code. I know that in operation in Operation 1-3 ASM Ops per entry can go.

The best solution I've found is:

  list.AddRange (notable. Repetition (empty, count list.account));  

However this can be the C # 3.0 (& lt; 3.0 priority) and the creation and evaluation of a calculator.

My current code uses it:

  while (list.Qount & lt; lim) list.Add (empty);  

That is the starting point for the cost of time.

It is that I need to set n'th element even though it is after old calculation.

The simplest way would be to create a temporary array:

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

Where size is the required new size, and the number of items in the count list is counted. However, for larger values ​​of size - count , this may be poor performance because it can allocate the list several times. ( * ) There is also the disadvantage of assigning an additional temporary array, which may not be acceptable depending on your requirements. You can reduce both issues at the expense of a more precise code by using the following methods:

  Up to public static class collections {public static list & lt; T & gt; Make sure that & lt; T & gt; (This list & lt; T & gt; list, integer shape) {make sure return (list, size, default (T)); } Public static list & lt; T & gt; Make sure that & lt; T & gt; (This list & lt; T & gt; list, integer shape, T value) {if (list == null) remove new logic ("list"); If (size & lt; 0) leave the new logic upOnxide ("size"); Int count = list.Qount; If (calculated & lt; size) {int capacity = list.Capacity; If (capacity & lt; size) list Capacity = math Maximum (size, capacity * 2); While (counting & lt; size) {list.Add (value); ++ count; }} Return list; }}  

Remove the modifier used to create the " this " modifier extension method only and it will work in C # 2.0.

Unfortunately, I have never compared the performance of two versions, so I do not know who is better.

Oh, and do you know that you can resize an array by calling? I did not know that :)

Update:
( * ) use list.AddRange (array) will not cause the reason for using a calculator. Looking forward through the reflector, it was discovered that the array was ICollection & lt; T & gt; , and the calculation property will be used so that allocation can be done only once.


Comments