c# - 最大尺寸字典的数据结构

标签 c# algorithm data-structures hash dictionary

<分区>

Possible Duplicate:
Is it there any LRU implementation of IDictionary?

我正在寻找一种类似于字典但只能包含一组键值对的数据结构。当一个键值对被添加到一个已经满的字典中时,一个最近没有被访问的键值对将被删除。

C# 是否已经存在类似的东西?

我记得为操作系统类实现了类似的东西,数据结构用于决定应将 RAM 的哪一部分分页到磁盘。这是通过将引用位与每个键值对相关联来完成的,该键值对在访问该对时设置为 true。当需要删除一对时,将迭代键值对,直到找到一个其引用位设置为 false 为止。迭代的每一对的引用位将被设置为假,最后一个将被删除。

如果 C# 中不存在用于此的数据结构,那么我描述的算法是否是实现它的好方法?

最佳答案

看起来 .Net 框架中还没有任何实现,所以这就是我最终使用的

using System.Collections.Generic;
using System.Linq;

namespace MyProject.Util
{
public class LruCache<Key, Value>
{
    public delegate Value ValueCreator();

    Dictionary<Key, ValueWithReference> cache;

    //The maximum number of elements that can fit in the cache.
    int maxCacheSize;

    IEnumerator<Value> valueRemover;

    public LruCache(int maxCacheSize) {
        this.cache = new Dictionary<Key, ValueWithReference>();
        this.maxCacheSize = maxCacheSize;
        this.valueRemover = GetKeyValuePairRemover().GetEnumerator();
    }

    /// <summary>
    /// Gets the value associated with the specified key. If it doesn't exist in the cache 
    /// then it will be created with createValue() and added to the cache. 
    /// </summary>
    public Value GetAndAddValue(Key key, ValueCreator createValue) {
        if (this.cache.ContainsKey(key) == false)
        {
            while (this.cache.Count >= this.maxCacheSize) {
                this.valueRemover.MoveNext();
            }

            this.cache[key] = new ValueWithReference(createValue());
        }

        this.cache[key].recentlyUsed = true;
        return this.cache[key].value;

    }

    protected IEnumerable<Value> GetKeyValuePairRemover() { 
        while (true) {
            List<Key> keyList = this.cache.Keys.ToList();

            foreach(Key key in keyList) {
                if (this.cache[key].recentlyUsed)
                {
                    this.cache[key].recentlyUsed = false;
                }
                else {
                    Value removedValue = this.cache[key].value;
                    this.cache.Remove(key);
                    yield return removedValue;
                }
            }

        }
    }

    protected class ValueWithReference
    {
        public Value value;
        public bool recentlyUsed;

        public ValueWithReference(Value value)
        {
            this.value = value;
            this.recentlyUsed = true;
        }
    }
}
}

关于c# - 最大尺寸字典的数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14676388/

相关文章:

c++ - 带有检查点的开源压缩算法

c# - C# 中固定深度的树状数据的最佳数据结构是什么?

c++ - 如何使 std::map 比较以处理多种数据类型?

C# 将位图转换为 FFmediaToolkits ImageData

c# - 在构建之前注入(inject) C# 代码

C# - 我知道,我知道,关于 Dispose 的另一个问题(与设计更相关)!

javascript - 绘制具有厚度/宽度的线的算法

c# - Entity Framework DbEntityEntry.Property 方法是否使用反射?

c - 用 C 编写一个程序,输出给定数字之间的丰富数字序列的第一项和项数

c++ - 处理霍夫曼压缩/解压缩中的最后一个字节