Search code examples
c#.netlinqcollections

Is there a .NET queue class that allows for dequeuing multiple items at once?


I believe a pretty common scenario is to have a queue of items that should be processed N at a time.

For instance.. if we have 23 items and should process 10 at a time, it would be like:

Process batch of 10
Process batch of 10
Process batch of 3

I can solve this problem in a variaty of ways. My question is: Does the .NET framework provide any class designed specifically to address this scenario? The Queue class would be perfect but it doesn't allow for dequeuing multiple items at once.


Solution

  • You could create an extension method on Queue<T>:

    public static class QueueExtensions
    {
        public static IEnumerable<T> DequeueChunk<T>(this Queue<T> queue, int chunkSize) 
        {
            for (int i = 0; i < chunkSize && queue.Count > 0; i++)
            {
                yield return queue.Dequeue();
            }
        }
    }
    

    Usage:

    var q = new Queue<char>();
    q.DequeueChunk(10) // first 10 items
    q.DequeueChunk(10) // next 10 items
    

    Example: https://dotnetfiddle.net/OTcIZX