UniqueQueue (listed) 21.01.2020 10:54:26 (40 lines) [Edit] [Raw] [View]

using System.Collections; using System.Collections.Generic;

namespace PgRr.System.Collections.Generic { public class UniqueQueue : IEnumerable, IEnumerable {

    private HashSet hashSet = new HashSet();
    private Queue queue = new Queue();

    public int Count => hashSet.Count;

    public void Clear() {
        hashSet.Clear();
        queue.Clear();
    }

    public bool Contains(T item) => hashSet.Contains(item);

    public void Enqueue(T item) {
        if (hashSet.Add(item)) {
            queue.Enqueue(item);
        } else {
            throw new InvalidOperationException("The queue already contains this item");
        }
    }

    public T Dequeue() {
        T item = queue.Dequeue();
        hashSet.Remove(item);
        return item;
    }

    public T Peek() => queue.Peek();

    public IEnumerator GetEnumerator() => queue.GetEnumerator();

    IEnumerator IEnumerable.GetEnumerator() => queue.GetEnumerator();

}

}