Search code examples
c#countkeyvaluepairsortedlist

Keep the most recent KeyValuePairs in a SortedList


I have a SortedList that adds KeyValuePairs every 10 min. I'm trying to keep the most recent 10 KeyValuePairs and remove all prior pairs but what I'm doing isn't working. Below I attached my code with explanation along each step. Any help is greatly appreciated.

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.

** In myList, the Key int is PlayerID# (which is random) and the Value is that Player's Score %

To answer your questions:

  • Sorting is not an issue with the current set up.
  • It does not have to be a SortedList, I'm open to any suggestion. I'm just more familiar with using Dictionaries and Lists.
  • I have never used a Queue but open to trying it. (Will have to research that, I'm learning something new everyday)
  • There are no time stamps and the timing of new entries is not important. All I'm trying to do is make sure that myList only has the most recent 10.

Solution

  • How about using a LinkedList instead of a SortedList.

    if(myLinkedList.Count() > 10)
        myLinkedList.RemoveFirst();
    

    This will always remove the first added item of the list.