How to "Dequeue" Element from a List?

You can do it in two steps:

String p1FirstCard = _deck[0];
_deck.RemoveAt(0);

You can write your own extension helper method (I added an index to Pop, as @Fredou suggested:

static class ListExtension
{
    public static T PopAt<T>(this List<T> list, int index)
    {
        T r = list[index];
        list.RemoveAt(index);
        return r;
    }
}

and then call

String p1FirstCard = _deck.PopAt(0);

P.S. The name can be a bit confusing. Pop usually removes the last element, not the first one.


If you want to dequeue the first element, you could simply use a Queue<T>.

class Program
{
    static void Main(string[] args)
    {
        var _deck = new Queue<String>();
        _deck.Enqueue("2h");
        _deck.Enqueue("3h");
        _deck.Enqueue("4h");
        _deck.Enqueue("...");

        var first = _deck.Dequeue(); // 2h
        first = _deck.Dequeue(); // 3h
    }
}

If you want to pop the last element, you could use a Stack<T>.

class Program
{
    static void Main(string[] args)
    {
        var _deck = new Stack<String>();
        _deck.Push("2h");
        _deck.Push("3h");
        _deck.Push("4h");
        _deck.Push("...");

        var first = _deck.Pop(); // ...
        first = _deck.Pop(); // 4h
    }
}

Tags:

C#

Arrays