How do you get the first and last items in the queue?

Let's say that I have a summary collection of values ​​where I specify the size of the collection and at any time a new value is added, all old values ​​that exceed the specified size are unloaded. Obviously (and I tested this) the best type of collection used for this behavior is the queue:

myQueue.Enqueue(newValue) If myQueue.Count > specifiedSize Then myQueue.Dequeue() 

However, if I want to calculate the difference between the first and last items in the queue? Obviously, I cannot access the elements by index. But switching from a queue to something that implements IList seems to be superfluous, like writing a new Queue class. Right now I have:

 Dim firstValue As Integer = myQueue.Peek() Dim lastValue As Integer = myQueue.ToArray()(myQueue.Count - 1) Dim diff As Integer = lastValue - firstValue 

This ToArray() call bothers me, but an excellent alternative does not suit me. Any suggestions?

+7
collections c # queue
source share
5 answers

One thing you can do is to have a temporary variable that stores a value that was simply queued up because it will be the last value, and therefore this variable can be accessed to get that value.

+14
source share

It seems to me that if you need quick access to the first element in the list, then you are using the wrong data structure. Instead, switch the LinkedList, which has the First and Last properties.

Be sure to add and remove items to the linked list using AddLast and RemoveFirst to save the Queue property. To prevent inadvertent violation of the Queue property, consider creating a wrapper class around the linked list and displaying only the necessary properties from your queue.

+10
source share
 public class LastQ<T> : Queue<T> { public T Last { get; private set; } public new void Enqueue(T item) { Last = item; base.Enqueue(item); } } 

Edit: Obviously, this base class needs to be more robust to do things like protecting the Last property on an empty queue. But this should be enough for the main idea.

+4
source share

It’s best to keep track of the last value added to Queue and then use the myQueue.Peek() function to see the β€œfirst” (meaning next) element in the list without deleting it.

+2
source share

You can use the deque queue ( d ouble e nded )

I do not think that there is one built in to System.Collections (.Generic), but here is some information about the data structure. If you applied something like this, you can just use PeekLeft () and PeekRight () to get the first and last values.

Of course, it is up to you whether it is preferable to implement your own deque to solve the recklessness problem of ToArray (). :)

http://www.codeproject.com/KB/recipes/deque.aspx

+1
source share

All Articles