首页 > 解决方案 > 将最新的 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 是该玩家的分数 %

要回答您的问题:

标签: c#countkeyvaluepairsortedlist

解决方案


我想要做的是将 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));

推荐阅读