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


- C# 中多线程网络服务器的模式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01