Exclude element from an array

Asked

Viewed 2,427 times

1

Need to delete the first element of an array.

Have: Numero[10].

How do I delete the value in Numero[0] and overwrite the other elements?

  • What would be "subscribing to the other elements"?

  • a suggestion would be to use Queues, (Queue)

  • Is it necessary to use Array even? You could use a List and then the method List.Remove

2 answers

4

var foos = new List<Foo>(array);
foos.RemoveAt(index);
return foos.ToArray();

You can try with extension method:

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;
}

Using like this:

Foo[] bar = GetFoos();
bar = bar.RemoveAt(2);

Source: https://stackoverflow.com/questions/457453/remove-element-of-a-regular-array

3


Need to delete the first element of an array

It is not possible to exclude a position or element from an array. If the array has 10 positions, it will always have 10 positions.

Use the method Clear() class Array for reset this array position to the default value of this type. For example:

int[] seuArray = new int[3];
seuArray[0] = 1;
seuArray[1] = 2;
seuArray[2] = 3;

Array.Clear(seuArray, 0, 1);

foreach (var x in arr) {
    Console.Write(x);
}

Upshot: 023

Being:

  • seuArray: the array in question
  • 0: From which position do you want to "clear"
  • 1: How many positions you want to clear

To overwrite the other positions just do:

seuArray[1] = 5;
seuArray[2] = 6;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.