Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary with item limit

Tags:

c#

dictionary

I need to provide access to a Key/Value pair store that persists for all users across session.

I could easily create a singleton for this, but for performance reasons I want to limit the size of the dictionary to 10000 items (or any performant number, as the object will persist indefinitely)

Is there a form of dictionary where I can specify a limit to the number of objects stored, and when that limit is exceeded, remove the oldest entry?

like image 358
Wesley Avatar asked Aug 18 '14 18:08

Wesley


People also ask

Is there a dictionary limit?

Normally, there's no accurate size or limit allotted to a Word dictionary. If you want to get additional information about it's size accommodation, you can contact our Word Expert using this link.

How large can a dictionary be C#?

The maximum capacity of a dictionary is up to 2 billion elements on a 64-bit system by setting the enabled attribute of the gcAllowVeryLargeObjects configuration element to true in the run-time environment.

Can a dictionary hold different data types?

One can only put one type of object into a dictionary. If one wants to put a variety of types of data into the same dictionary, e.g. for configuration information or other common data stores, the superclass of all possible held data types must be used to define the dictionary.


1 Answers

There is no such built-in dictionary, but you can build your own. You will need a queue for keys - that will allow you quickly find oldest entry and remove it. Also you will need a simple dictionary for keeping your values - that will allow you quickly search for them:

public class SuperDictionary<TKey, TValue>
{
    private Dictionary<TKey, TValue> dictionary;
    private Queue<TKey> keys;
    private int capacity;

    public SuperDictionary(int capacity)
    {
        this.keys = new Queue<TKey>(capacity);
        this.capacity = capacity;
        this.dictionary = new Dictionary<TKey, TValue>(capacity);
    }

    public void Add(TKey key, TValue value)
    {
        if (dictionary.Count == capacity)
        {
            var oldestKey = keys.Dequeue();
            dictionary.Remove(oldestKey);
        }

        dictionary.Add(key, value);
        keys.Enqueue(key);
    }

    public TValue this[TKey key]
    {
        get { return dictionary[key]; }
    }
}

NOTE: You can implement IDictionary<TKey,TValue> interface, to make this class a 'true' dictionary.

like image 159
Sergey Berezovskiy Avatar answered Sep 24 '22 19:09

Sergey Berezovskiy