c# - 将最新的 KeyValuePairs 保存在 SortedList 中
问题描述
我有一个 SortedList 每 10 分钟添加一次 KeyValuePairs。我正在尝试保留最近的 10 个 KeyValuePairs 并删除所有先前的对,但我正在做的事情不起作用。下面我附上了我的代码以及每个步骤的解释。任何帮助是极大的赞赏。
private SortedList<int, double> myList = new SortedList<int, double>();
// Every 10 minutes a new KeyValuePair is added to myList so
// I have no issue with sorting. I'm only trying to get the most
// recent 10 KeyValuePairs.
// My Attempt (the only one that worked without errors)
int mylistCount = 10;
if (myList.Count()>mylistCount)
{myList.Clear();}
// The issue with my attempt is that it erases the entire myList
// As a result, whenever myList reaches 10, it goes back to Zero.
// What I'm trying to do is keep myList Count at 10 containing only
// the most recent KeyValuePairs.
** 在 myList 中,Key int 是 PlayerID#(随机),Value 是该玩家的分数 %
要回答您的问题:
- 排序不是当前设置的问题。
- 它不一定是 SortedList,我愿意接受任何建议。我只是更熟悉使用字典和列表。
- 我从未使用过队列,但愿意尝试。(必须研究一下,我每天都在学习新东西)
- 没有时间戳,新条目的时间也不重要。我要做的就是确保 myList 只有最近的 10 个。
解决方案
我想要做的是将 myList Count 保持在 10,仅包含最近的 KeyValuePairs。
你想保留最近的 10 对,所以我假设排序是按添加时间。如果这是真的,您不需要对它们进行排序,因此不需要SortedList
. 您可以Queue
按照评论中的建议使用 a 。
队列是先进先出 (FIFO)。这意味着您知道队列中的第一个元素是最旧的,并且当第十一个元素进入时您需要出列。例如,这不能用一点仪式来解决问题吗?
// q is a Queue (FIFO)
if (q.Count == 10)
{
// we've reached our cap, remove the element at the
// front of the q (the oldest one)
q.Dequeue();
}
// we'll always add the newest element to the end of the q
q.Enqueue(new KeyValuePair<int, double>(key, value));
推荐阅读
- java - 如何保持用户输入的精度?
- html - 将网站部署到 Github 时没有出现 FontAwesome 图标
- javascript - 在最终应用中使用剧作家(电子)
- python - 自动化,预定测试
- flutter - 我从 pub dev 添加了 audioplayers 0.19.1 包,但是当我运行 pub get 时,我遇到了错误,无法创建链接,我不知道发生了什么
- docker - 如何在执行 Docker 构建时禁用加载元数据?
- webpack - 生成图像路径的 Webpack 问题
- python - 演示语音情感分析器上的一些错误( IsADirectoryError: [Errno 21] Is a directory: 'input/English/.ipynb_checkpoints')
- flutter - 在颤动中同时读取和写入数据到数据库
- assembly - BIOS 调用的引导加载程序键盘输入问题