Is there a Pop() equivalent in C# HashSet

Viewed 2774

If I have a non-empty HashSet<T> items, is there any shortcut for those two lines:

T item = items.First(); // this can be any item, it does not have to be the first one
items.Remove(item);

I thought T item = items.Pop() would be a proper function for this, but it does not exists.

I know, it is no big deal having both lines or write an extension method, but I somehow expected a build-in Pop()-function, which does not rely on First().

Edit:

Since there is some confusion about First(): I absolutely do not care about which item is popped from the HashSet, so items.Last() would be ok for me as well.

This confusion about using First() is the point I am struggeling with: Even I commented it, reading the code lead to the assumption, it is somehow important to use First() (which is not).

So to clarify it: I wonder, if there is a proper way, to take some item from a HashSet, have it for further usage and do not give the impression, it has to be the first or last or whatever item, but rather be clear, that any item could have been picked at this point.

1 Answers

This is an elegant solution (i used list but you can put hashset instead of it):

class Program
{
    static void Main(string[] args)
    {
        List<object> items = new List<object>();
        //code to fill the list...
        object item = items.RemoveFirst();
    }
}

static class Extensions
{
    public static T RemoveFirst<T>(this ICollection<T> items)
    {
        T item = items.FirstOrDefault();
        if (item != null)
        {
            items.Remove(item);
        }
        return item;
    }
}
Related