Remove or insert an item in an array.
Use the always useful Array class. It has some static members which are great!
int[] myArray = new int[4]; myArray [0] = 0; myArray [1] = 1; myArray [2] = 2; myArray [3] = 3; // Remove item 1 Array.Copy(myArray , 2, myArray , 1, 2); // MyArray contains 0,2,3,3 myArray [0] = 0; myArray [1] = 1; myArray [2] = 2; myArray [3] = 3; // Insert new item in 1 Array.Copy(myArray , 1, myArray ,2, 2); // MyArray contains 0,1,1,2
Note: If the bounds of the array are exceeded an exception will be thrown.
The functions below calculate the number of elements to copy.
They use the following arguments:
Array | The array to use. |
index | The offset whereto insert or remove |
delta | The number of items to add / remove |
totCount | The number of items currently in the array. |
To allow a correct insert the array must be larger than the current numbers (Arrays are not resized). Clearing is optional
void removeFromArray(Array array, int index, int delta, int totCount) { Array.Copy(array, index + delta, array, index, totCount - (index + delta)); Array.Clear(array, totCount - delta, delta); } void insertIntoArray(Array array, int index, int delta, int totCount) { Array.Copy(array, index, array, index + delta, totCount - index); Array.Clear(array, index, delta); }