时间:2019-03-17 标签:c#limitedDictionary
我想建立一个字典(键,值), 但我希望这本词典的大小有限, 例如 1000 个条目, 所以当我丰富这个限制大小时,我想删除第一个元素并添加一个新元素(FIFO)。
我想使用字典,因为我总是在字典中搜索键(我需要它会很快)
如何做到这一点?
I want to build a Dictionary (key, value),
but I want that this Dictionary have limited size,
for example 1000 entries,
so when I rich this limit size, I want to remove the first element and add a new element(FIFO).
I want to use dictionary because I am always searching keys in the dictionary (i need that it will be fast)
How to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要获取字典和 LIFO/FIFO 行为(用于删除最新/最旧的条目),您可以使用
OrderedDictionary
。请参阅 http://msdn.microsoft.com/en -us/library/system.collections.specialized.ordereddictionary.aspx。为了方便使用,您可以按照 @ArsenMkrt 建议的方式从
OrderedDictionary
派生您自己的类。但请注意,
OrderedDictionary
不使用泛型,因此由于装箱,会出现一些低效率(字典中的项目将作为object
插入)。克服这个问题的唯一方法是创建一个双数据结构,将字典中的所有项目镜像到队列(对于 FIFO)或堆栈(对于后进先出)中。有关详细信息,请参阅“Qua”对以下 SO 问题的回答,该问题恰好处理您需要一种有效方法来跟踪字典项插入顺序的情况。C# 中最快、最高效的集合类型
To get both a dictionary and either LIFO/FIFO behavior (for deleting newest/oldest entry), you can use an
OrderedDictionary
. See http://msdn.microsoft.com/en-us/library/system.collections.specialized.ordereddictionary.aspx.To make this convenient to use, you could derive your own class from
OrderedDictionary
, along the lines suggested by @ArsenMkrt.Note, however, that
OrderedDictionary
does not use Generics, so there will be some inefficency due to boxing (items in the dictionary will be inserted asobject
). The only way to overcome this is to create a dual data structure which has all items in the dictionary mirrored in aQueue
(for FIFO), or aStack
(for LIFO). For details see the answer by "Qua" to the following SO question, which deals with precisely the situation where you need an efficient way keep track of the order in which dictionary items were inserted.Fastest and most efficient collection type in C#
像这样从字典和 ovverride 添加方法派生
Derive from dictionary and ovverride add method like this
我不知道我们是否可以明确限制字典的大小。不久前我也想做同样的事情。
我通过编写一种方法解决了这个问题,该方法不断手动检查字典计数,当其大小超过一定限制时,它将从字典中删除一些条目。
I dont know whether we can limit the dictionary size explicitly. Sometime back I wanted to do the same.
I solved the problem by writting one method which keeps checking the dictionary count manually and when its size exceeded beyond certain limit, it will remove some entries from dictionary.