Remove element from a vector in C # and not leave the vector with a space?

5

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.

    
asked by anonymous 11.03.2016 / 00:00

2 answers

7

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.

    
11.03.2016 / 00:14
1

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;
    // ...
}
    
19.11.2017 / 00:24