Beispiel #1
0
        /// <summary>
        /// Adds a new element to the cache, replacing and moving it to the front if the
        /// element is already present.
        /// </summary>
        public void Add(TKey key, TValue value)
        {
            KeyInfo keyInfo;

            if (_dict.TryGetValue(key, out keyInfo))
            {
                // remove original entry from the linked list
                _list.Remove(keyInfo.List);
            }
            else if (_list.Count == _maxSize)
            {
                // we've reached capacity, remove the last used element...
                LinkedListNode <TKey> node = _list.Last;
                _list.RemoveLast();
                bool res = _dict.Remove(node.Value);
                Debug.Assert(res);
            }

            // add the new entry to the head of the list and into the dictionary
            LinkedListNode <TKey> listNode = new LinkedListNode <TKey>(key);

            _list.AddFirst(listNode);
            _dict[key] = new CacheDict <TKey, TValue> .KeyInfo(value, listNode);
        }