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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With