您将如何获得队列中的第一个和最后一个项目?

How would you obtain the first and last items in a Queue?(您将如何获得队列中的第一个和最后一个项目?)
本文介绍了您将如何获得队列中的第一个和最后一个项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个滚动值集合,我在其中指定集合的​​大小,并且任何时候添加新值,超过此指定大小的任何旧值都会被丢弃.显然(并且我已经对此进行了测试)用于此行为的最佳集合类型是队列:

Say I have a rolling collection of values where I specify the size of the collection and any time a new value is added, any old values beyond this specified size are dropped off. Obviously (and I've tested this) the best type of collection to use for this behavior is a Queue:

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

但是,如果我想计算队列中第一项和最后一项之间的差异,该怎么办?显然我无法通过索引访问这些项目.但是从 Queue 切换到实现 IList 的东西似乎有点矫枉过正,编写一个新的类似 Queue 的类也是如此.现在我有:

However, what if I want to calculate the difference between the first and last items in the Queue? Obviously I can't access the items by index. But to switch from a Queue to something implementing IList seems like overkill, as does writing a new Queue-like class. Right now I've got:

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

ToArray() 的调用让我感到困扰,但我并没有找到更好的选择.有什么建议吗?

That call to ToArray() bothers me, but a superior alternative isn't coming to me. Any suggestions?

推荐答案

你可以做的一件事是有一个临时变量来存储刚刚入队的值,因为那将是最后一个值,因此可以访问该变量得到那个值.

One thing you could do is have a temporary variable that stores the value that was just enqueued because that will be the last value and so the variable can be accessed to get that value.

这篇关于您将如何获得队列中的第一个和最后一个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)