List.Pop

I started writing a little WPF card game and kept coming up against having to remove and store an item from the list – essentially a pop operation.  So I wrote the following extension method.

public static class ListPopper
{
    public static T Pop<T>(this IList<T> list)
    {
        T value = list.FirstOrDefault();

        list.Remove(value);

        return value;
    }
}

I eventually decided to switch to a Stack for the card game – but I think the extension method may come in handy for other projects.

Leave a Comment

Powered by WP Hashcash