How can I insert elements into a Queue in C#

23,913

Solution 1

A queue, by definition, is something to which you can only enqueue and dequeue things. If you want to insert in the middle, then you want a full-fledged list (probably LinkedList<T>), not a Queue.

I mean, you woulnd't try to "insert" yourself in the middle of the queue in a supermarket (I hope); it works the same way here.

Solution 2

What you're looking for is a LinkedList<T>. You can add to the beginning, middle (using AddBefore or AddAfter), or end of the list.

This is advantagous over using a List<T> because you can then use RemoveFirst or RemoveLast to have it imitate more closely a Queue or a Stack.

Solution 3

While the answers on this page are correct if you find yourself in a position where you can't use something other than a queue you can (with a bit of overhead) add an item into the middle of a queue. Whether it should be done or not is a different story.

var myQueue = new Queue<string>();
myQueue.Enqueue("item 0");
myQueue.Enqueue("item 10");

var myList = myQueue.ToList();
myList.Insert(1, "item 5");

myQueue = new Queue<string>(myList);

Solution 4

The point of a queue is to provide a FIFO (first-in-first-out) interface abstraction. If you want to be able to interact with your data structure in a non-queue way, don't use a queue.

Solution 5

You will probably have to use a List.

Share:
23,913

Related videos on Youtube

Bastien Vandamme
Author by

Bastien Vandamme

Updated on July 01, 2022

Comments

  • Bastien Vandamme
    Bastien Vandamme almost 2 years

    In C# I use a Queue collection. I can easily Enqueue or Dequeue. Okay, now I would like to insert something in the middle of the queue or at the beginning of the queue. I don't find any method to do such thing. What do you recommend as the alternate collection?

    • Lasse V. Karlsen
      Lasse V. Karlsen over 14 years
      ... don't tell me, you're one of those guys that try to enter a queue in the middle at the supermarket as well? :) My point is that the entire point of a queue is that items enter it at one end, and leave at another. Now, I'll leave it as an excercise for the reader to figure out how people leaving the queue can be implemented :)
  • ToolmakerSteve
    ToolmakerSteve about 6 years
    Useful technique. Be aware that because you are creating a new Queue, anyone with a reference to the old Queue will not see your insertion! Sometimes is OK, if the old queue is passed in "by reference" AND no one else has "squirreled away" a reference to the old queue. The latter requirement is the problem: if you can't change the class you are using, you probably also don't have a guarantee that you are allowed to make a new object. In such a case, it is necessary to Dequeue all the items into your temp list, insert, then Enqueue them all again.

Related