7

我需要一个可以存储密钥和项目的环列表字典。Capacity = 50当我添加#51第一项时,必须删除。基本上它必须是一个表现得像一个环形列表的字典。

.NET Framework 中有什么可以做到这一点吗?还是我必须自己写?

4

3 回答 3

5

我认为你不会找到任何内置的东西,但你可以使用OrderedDictionary轻松实现一个

OrderedDictionary按照插入的顺序维护项目。每当您达到限制/容量时,您都可以删除第一个项目。

于 2013-08-06T10:39:26.350 回答
3

或使用扩展方法:

编辑 :

因为

最新添加的条目最终会首先返回。

所以你可以删除第一个项目,如:

dictionary.Remove(dictionary.Last().Key);  

& 所以你的扩展方法是:

addExtension(this Dictionary<string, object> dictionary, string key, object value)
   {
        if(dictionary.Count == 50)
                dictionary.Remove(dictionary.Last().Key);  

        dictionary.Add(key, value);   
   }
于 2013-08-06T10:55:57.903 回答
2

尝试这个:

class Program
{
    static void Main(string[] args)
    {
        var rD = new RingDictionary(50);
        for (int i = 0; i < 75; i++)
        {
            rD.Add(i, i);
        }
        foreach (var item in rD.Keys)
        {
            Console.WriteLine("{0} {1}", item, rD[item]);
        }
    }
}

class RingDictionary : OrderedDictionary
{
    int indexKey;

    int _capacity = 0;
    public int Capacity
    {
        get { return _capacity; }
        set
        {
            if (value <= 0)
            {
                var errorMessage = typeof(Environment)
                    .GetMethod(
                        "GetResourceString",
                        System.Reflection.BindingFlags.Static |
                        System.Reflection.BindingFlags.NonPublic,
                        null,
                        new Type[] { typeof(string) },
                        null)
                    .Invoke(null, new object[] { 
                        "ArgumentOutOfRange_NegativeCapacity" 
                    }).ToString();
                throw new ArgumentException(errorMessage);
            }
            _capacity = value;
        }
    }

    public RingDictionary(int capacity)
    {
        indexKey = -1;
        Capacity = capacity;
    }

    public new void Add(object key, object value)
    {
        indexKey++;

        if (base.Keys.Count > _capacity)
        {
            for (int i = base.Keys.Count-1; i >Capacity-1 ; i--)
            {
                base.RemoveAt(i);
            }
        }

        if (base.Keys.Count == _capacity)
        {
            base.RemoveAt(indexKey % _capacity);
            base.Insert(indexKey % _capacity, key, value);
        }
        else
        {
            base.Add(key, value);
        }
    }
}
于 2013-08-06T11:00:17.283 回答