How to remove the first item from an array without for or foreach

0

How to remove the first item from a non-foreach array.

I have tried this, but it says that there is no remove or removeAt method.

int[] arr = {1,2,3,4,5};

var removeu = Array.Remove(arr,0);//Agora percebi que isso é javascript, rs

This gives error. How I do? I passed this to a list, but it made a mistake too.

List<int> lista = new List<int>(arr);

lista.Remove(0); // The zero here is not the first index.

How do I do it now?

    
asked by anonymous 06.07.2015 / 22:57

3 answers

4

Use the following code:

List<int> arr = new List<int>(new int[]{1, 2, 3, 4, 5});
arr.RemoveAt(0);

Source: link

If you want to recover it before, use:

var primeiro = arr.First();

Source: link

    
06.07.2015 / 23:05
3

According to the comment what you want to do is this:

var primeiro = arr.RemoveAt(0);

Only an array does not have the RemoveAt method so you have to create an extension method like this removed from the OS :

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;
}
    
06.07.2015 / 23:09
1

If you are always going to add elements at the end and remove them from the beginning, you can use the class Queue , which is a first in first out, that is, whenever you remove it will be from the beginning, example:

        Queue<int> fila= new Queue<int>();
        fila.Enqueue(1); //adiciona valor 1
        fila.Enqueue(2); //adiciona valor 2
        fila.Enqueue(3); //adiciona valor 3
        fila.Enqueue(4); //adiciona valor 4
        fila.Enqueue(5); //adiciona valor 5

        fila.Dequeue();//remove o primeiro elemento, neste caso o 1

If this is the case, the best data structure to use is this.

    
07.07.2015 / 00:10