/Main/src/DynamicDataDisplay/Common/RingDictionary.cs
C# | 64 lines | 50 code | 10 blank | 4 comment | 2 complexity | 3a73d5b6ed309cbb1698f97fb8899011 MD5 | raw file
Possible License(s): CC-BY-SA-3.0
1using System; 2using System.Collections.Generic; 3using System.Linq; 4using System.Text; 5using System.Diagnostics.Contracts; 6 7namespace Microsoft.Research.DynamicDataDisplay.Common 8{ 9 /// <summary> 10 /// Represents a dictionary with automatic removal of old values. 11 /// </summary> 12 /// <typeparam name="T"></typeparam> 13 public sealed class RingDictionary<T> 14 { 15 private int startGeneration = 0; 16 private int generation; 17 private readonly Dictionary<int, T> dict = new Dictionary<int, T>(); 18 private readonly int maxElements = 5; 19 20 public RingDictionary(int maxElements = 5) 21 { 22 Contract.Assert(maxElements >= 1); 23 24 this.maxElements = maxElements; 25 } 26 27 public int Generation 28 { 29 get { return generation; } 30 } 31 32 public int StartGeneration 33 { 34 get { return startGeneration; } 35 } 36 37 public bool ContainsValue(T value) 38 { 39 return dict.ContainsValue(value); 40 } 41 42 public void AddValue(T value) 43 { 44 Contract.Assert(value != null); 45 46 dict.Add(generation++, value); 47 Cleanup(); 48 } 49 50 public int Count 51 { 52 get { return dict.Count; } 53 } 54 55 private void Cleanup() 56 { 57 while ((generation - startGeneration) > maxElements) 58 { 59 dict.Remove(startGeneration); 60 startGeneration++; 61 } 62 } 63 } 64}