private void Shrink() { int removed = 0; int toRemove = dictionary.Count - (int)(shrinkFactor * capacity); while (removed < toRemove) { LinkedDictionary <TKey, ValueWrapper> dict = GetDictByFrequency(lowestFrequency); if (dict.Count == 0) { throw new Exception(); } while (dict.Count > 0 && removed < toRemove) { var key = dict.FirstKey; bool r = dict.Remove(key); dictionary.Remove(key); ++removed; } if (dict.Count == 0) { UpdateLowestFrequency(); } } }
public TValue this[TKey key] { get { if (TryGetValue(key, out TValue value)) { return(value); } throw new KeyNotFoundException(); } set { linkedDictionary.Remove(key); linkedDictionary.AddFirst(key, value); if (linkedDictionary.Count > capacity) { linkedDictionary.Remove(linkedDictionary.LastKey); } } }
public TValue this[TKey key] { get { return(linkedDictionary[key]); } set { if (linkedDictionary.Remove(key)) { linkedDictionary.AddLast(key, value); } else { if (linkedDictionary.Count + 1 > capacity) { linkedDictionary.Remove(linkedDictionary.FirstKey); } linkedDictionary.AddLast(key, value); } } }
public bool Remove(TKey key) { ValueWrapper wrapper = default; if (dictionary.TryGetValue(key, out wrapper)) { LinkedDictionary <TKey, ValueWrapper> dict = GetDictByFrequency(wrapper.frequency); dict.Remove(key); if (lowestFrequency == wrapper.frequency) { UpdateLowestFrequency(); } return(true); } else { return(false); } }
public bool TryGetValue(TKey key, out TValue value) { ValueWrapper wrapper = default; if (dictionary.TryGetValue(key, out wrapper)) { int currentFrequency = wrapper.frequency; if (currentFrequency < maxFrequency) { int nextFrequency = currentFrequency + 1; LinkedDictionary <TKey, ValueWrapper> curDict = GetDictByFrequency(currentFrequency); LinkedDictionary <TKey, ValueWrapper> nextDict = GetDictByFrequency(nextFrequency); curDict.Remove(key); nextDict.Add(key, wrapper); wrapper.frequency = nextFrequency; dictionary[key] = wrapper; if (lowestFrequency == currentFrequency && curDict.Count == 0) { lowestFrequency = nextFrequency; } } else { // f相同时 用LRU策略 LinkedDictionary <TKey, ValueWrapper> dict = GetDictByFrequency(currentFrequency); dict.Remove(key); dict.Add(key, wrapper); } value = wrapper.value; return(true); } else { value = default; return(false); } }