辞典项限制 [英] Dictionary with item limit
问题描述
我需要提供访问键/值对商店仍然存在跨会话的所有用户。
I need to provide access to a Key/Value pair store that persists for all users across session.
我可以很容易地创建此单身,但是对于性能原因我想限制字典10000项的大小(或任何高性能的数量,对象将无限期地持续)
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?
推荐答案
有没有这种内置的字典,但你可以建立自己的。您将需要密钥的队列 - 这将让你迅速找到最旧的条目并删除它。你还需要一个简单的字典保持你的价值观 - 这将允许您快速搜索它们:
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]; }
}
}
请注意:您可以实施 IDictionary的< TKEY的,TValue方式>
接口,使这一类真实字典
NOTE: You can implement IDictionary<TKey,TValue>
interface, to make this class a 'true' dictionary.
这篇关于辞典项限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!