I need to remove an element from a vector with 5 elements, and can not have empty space in the vector.
I need to remove by index.
I need to remove an element from a vector with 5 elements, and can not have empty space in the vector.
I need to remove by index.
It does not work efficiently. You can do this:
var array = { 1, 2, 3, 4, 5 }
array = array.Where(item => item != 3).ToArray(); //retira o 4o. elemento
If you do not want to use LINQ:
var array = { 1, 2, 3, 4, 5 }
array = = Array.FindAll(numbers, x => x != 3).ToArray(); //retira o 4o. elemento
Or you can do an extension method to have a removeAt()
(that exists in a List) in Array
:
public static T[] RemoveAt<T>(this T[] source, int index) {
T[] dest = new T[source.Length - 1];
if( index > 0 )
Array.Copy(source, 0, dest, 0, index);
if( index < source.Length - 1 )
Array.Copy(source, index + 1, dest, index, source.Length - index - 1);
return dest;
}
Font .
Not even a list could do this efficiently. A linked list would even yield efficiency to some extent.
To complement the existing answer, it may be worth revisiting the need to use an array. When dealing with adding and removing elements, it is interesting to use a collection type. From the documentation, see how to choose the ideal type for what is dealing.
There's no way to resize an array without a high price. You must create an entirely new array with the copy of the items. This is what Array.Resize()
does in the final account , see:
T[] newArray = new T[newSize];
Array.Copy(larray, 0, newArray, 0, larray.Length > newSize? newSize : larray.Length);
array = newArray;
In cases where you have a fixed size of items and need performance, using an array can be advantageous, especially if you need to access items multiple times. See the benchmarking test done in the SOen:
List/foreach: 3054ms (589725196)
Array/foreach: 1860ms (589725196)
To save specific data as a bitmap of an image, an array is what you are looking for. Notice that these are very specific cases. Most often you will use List<T>
instead of an array in those purposes.
It's important to note that below the wipes List<T>
uses an array:
public class List<T> : IList<T>, System.Collections.IList, IReadOnlyList<T>
{
private T[] _items;
// ...
}