C# - 带有环列表行为的字典?

Bit*_*lue 7 c# dictionary list

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

.NET Framework中有什么可以做到的吗?或者我必须自己写吗?

Har*_*san 5

我不会发现任何内置的内容,但您可以使用OrderedDictionary轻松实现

OrderedDictionary按顺序维护项目.每当达到限制/容量时,您可以删除第一个项目.


Ale*_*ici 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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)