Hi all,
It is possible to remove array elements like the first 2 elements of each array
Thanks,
Aw
Hi all,
It is possible to remove array elements like the first 2 elements of each array
Thanks,
Aw
You cannot remove elements from an array, you can set elements to null.
You can use a list instead of an array and then u'll have the option to remove elements
Thanks for replying.
If I set the first 2 elements to null, will it change the length of the array If not, should I use list like you said But I wonder what's the advantage and disadvantages of it over the array
Thanks again,
Aw
It doesn't change the length of the array, you will have to check for nulls in your code.
Array is better for performance. For example you can find an element for a given index very fast - the length of the array does not matter. With list you can add and remove elements from any position, and do iterations on the list elements (using foreach loop)
Use Array.Copy and then Array.Resize. See this thread: Remove an object from the middle of an array.
Yes, there is a performance penalty to using Resize, it must allocate a new array and copy the elements from the source array to the new array. The original array will then be using memory until the next GC occurs.
If you have a collection that you need to remove items from, I recommend using an indexable collection that supports element removal with O(n) (linear) performance, like List<T>
A list is different than an array in that an array allocates a contiguous chunk of memory to store the data. A list, depending upon implementation, allocates chunks of data as time goes on. The default for List is to double its size whenever it runs out of space. You can override this by specifying a size when you create the list and avoid having to reallocate chunks as you add data. For example:
List myList new List(10);
// call add 10 times...
The above would avoid having to reallocate the backing store for the list 3 times. (starts with 0 elements, starts with a minimum of 4, then doubles afterwards. So, if you know you will have 10 elements, List(10) will have roughly the same performance and footprint as int[10];
You should always try to preallocate your list if you know or can estimate it's size. The following is not efficient:
List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);
list.Add(5);
list.Add(6);
list.Add(7);
list.Add(8);
list.Add(9);
list.Add(10);
When I remove an element form a list how are the indexes adjusted
e.g.:
I remove element with index 5 from list of 10 elements: (indexes):
1,2,3,4,5,6,7,8,9,0
will the indexes will be 1 to 9 with the shift left:
6 -> 5
7 -> 6 ...
or will remain as they are
Thank you
Sergey.