c# - Dictionary with item limit -
i need provide access key/value pair store persists users across session.
i create singleton this, performance reasons want limit size of dictionary 10000 items (or performant number, object persist indefinitely)
is there form of dictionary can specify limit number of objects stored, , when limit exceeded, remove oldest entry?
there no such built-in dictionary, can build own. need queue keys - allow find oldest entry , remove it. need simple dictionary keeping values - allow search 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] { { return dictionary[key]; } } }
note: can implement idictionary<tkey,tvalue>
interface, make class 'true' dictionary.
Comments
Post a Comment