PageRenderTime 42ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/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
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Diagnostics.Contracts;
  6. namespace Microsoft.Research.DynamicDataDisplay.Common
  7. {
  8. /// <summary>
  9. /// Represents a dictionary with automatic removal of old values.
  10. /// </summary>
  11. /// <typeparam name="T"></typeparam>
  12. public sealed class RingDictionary<T>
  13. {
  14. private int startGeneration = 0;
  15. private int generation;
  16. private readonly Dictionary<int, T> dict = new Dictionary<int, T>();
  17. private readonly int maxElements = 5;
  18. public RingDictionary(int maxElements = 5)
  19. {
  20. Contract.Assert(maxElements >= 1);
  21. this.maxElements = maxElements;
  22. }
  23. public int Generation
  24. {
  25. get { return generation; }
  26. }
  27. public int StartGeneration
  28. {
  29. get { return startGeneration; }
  30. }
  31. public bool ContainsValue(T value)
  32. {
  33. return dict.ContainsValue(value);
  34. }
  35. public void AddValue(T value)
  36. {
  37. Contract.Assert(value != null);
  38. dict.Add(generation++, value);
  39. Cleanup();
  40. }
  41. public int Count
  42. {
  43. get { return dict.Count; }
  44. }
  45. private void Cleanup()
  46. {
  47. while ((generation - startGeneration) > maxElements)
  48. {
  49. dict.Remove(startGeneration);
  50. startGeneration++;
  51. }
  52. }
  53. }
  54. }