开发者

How can I insert elements into a Queue in C#

开发者 https://www.devze.com 2022-12-10 17:01 出处:网络
In C# I use a Queue collection. I can easily Enqueue or Dequeue. Okay, now I would lik开发者_如何学运维e to insert something in the middle of the queue or at the beginning of the queue. I don\'t find

In C# I use a Queue collection. I can easily Enqueue or Dequeue. Okay, now I would lik开发者_如何学运维e 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?


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.


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.


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);


You will probably have to use a List.


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.


If you want to insert into "middle" of a queue, you might be looking for a "Priority Queue".

Unfortunately, that is not a built-in .Net class, AFAIK. But at least now you have a concept name, to search for.

See this (closed) Q&A for some possibly useful links:
Priority queue in .Net

Quoting from the question there:

Priority queues are data structures that provide more flexibility than simple sorting, because they allow new elements to enter a system at arbitrary intervals. It is much more cost-effective to insert a new job into a priority queue than to re-sort everything on each such arrival.

The basic priority queue supports three primary operations:

  • Insert(Q,x). Given an item x with key k, insert it into the priority queue Q.
  • Find-Minimum(Q). Return a pointer to the item whose key value is smaller than any other key in the priority queue Q.
  • Delete-Minimum(Q). Remove the item from the priority queue Q whose key is minimum
0

精彩评论

暂无评论...
验证码 换一张
取 消