/// <summary> /// Tries to get the value associated with 'key', returning true if it's found and /// false if it's not present. /// </summary> public bool TryGetValue(TKey key, out TValue value) { KeyInfo storedValue; if (_dict.TryGetValue(key, out storedValue)) { CustomLinkedListNode <TKey> node = storedValue.List; if (node.Previous != null) { // move us to the head of the list... _list.Remove(node); _list.AddFirst(node); } value = storedValue.Value; return(true); } value = default(TValue); return(false); }
public void RemoveLast() { if (_count == 0) { throw new InvalidOperationException("List empty"); } var node = _lastNode; _lastNode = _lastNode.Previous; _lastNode.Next = null; node.List = null; node.Previous = null; _count--; if (_lastNode == null) { _firstNode = null; } }
public void AddFirst(CustomLinkedListNode <T> node) { if (node.List != null) { throw new InvalidOperationException("Node belongs to another list"); } if (_firstNode != null) { _firstNode.Previous = node; } node.List = this; node.Next = _firstNode; _count++; _firstNode = node; if (_lastNode == null) { _lastNode = node; } }
/// <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... CustomLinkedListNode <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 CustomLinkedListNode <TKey> listNode = new CustomLinkedListNode <TKey>(key); _list.AddFirst(listNode); _dict[key] = new CacheDict <TKey, TValue> .KeyInfo(value, listNode); }
public void Remove(CustomLinkedListNode <T> node) { if (node == null) { throw new ArgumentNullException("node is null"); } if (node.List != this) { throw new InvalidOperationException("Node belongs to another list"); } if (node.Previous != null) { node.Previous.Next = node.Next; } else { _firstNode = node.Next; } if (node.Next != null) { node.Next.Previous = node.Previous; } else { _lastNode = node.Previous; } _count--; node.List = null; node.Next = null; node.Previous = null; }
internal KeyInfo(TValue value, CustomLinkedListNode <TKey> list) { Value = value; List = list; }