PageRenderTime 124ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/Utilities/Collections/UniqueHashtable.cs

#
C# | 78 lines | 50 code | 3 blank | 25 comment | 2 complexity | 9d1c1bd85ad60c5c7c8bc86f4e63413b MD5 | raw file
Possible License(s): Apache-2.0
  1. using System;
  2. using System.Collections;
  3. using NUnit.Framework;
  4. namespace Delta.Utilities.Collections
  5. {
  6. /// <summary>
  7. /// Exactly the same as the Hashtable, but adds only new key/value pairs
  8. /// if the key does not currently exists (the key is unique). This class
  9. /// also enforces KeyType and ValueType unlike Hashtable, which accepts
  10. /// all kind of objects.
  11. /// </summary>
  12. [Serializable]
  13. public class UniqueHashtable<TKeyType, TValueType> : Hashtable
  14. {
  15. #region Add (Public)
  16. /// <summary>
  17. /// Add new key/value pair, will not add if the key does already exists!
  18. /// </summary>
  19. /// <param name="key">Key</param>
  20. /// <param name="val">val</param>
  21. public void Add(TKeyType key, TValueType val)
  22. {
  23. if (!Contains(key))
  24. {
  25. base.Add(key, val);
  26. }
  27. }
  28. #endregion
  29. #region WriteKeys (Public)
  30. /// <summary>
  31. /// Write all keys into a string for output/debug/tracing/etc.
  32. /// </summary>
  33. /// <returns>Output string with all the values.</returns>
  34. public string WriteKeys()
  35. {
  36. string ret = "";
  37. foreach (object obj in Keys)
  38. {
  39. ret +=
  40. ret.Length == 0
  41. ? ""
  42. : ", " + obj;
  43. }
  44. return ret;
  45. }
  46. #endregion
  47. }
  48. /// <summary>
  49. /// Test unique hashtable
  50. /// </summary>
  51. internal class TestUniqueHashtableHelper
  52. {
  53. #region TestAddingData (Public)
  54. /// <summary>
  55. /// Test adding data
  56. /// </summary>
  57. [Test]
  58. public void TestAddingData()
  59. {
  60. UniqueHashtable<int, int> testTable = new UniqueHashtable<int, int>();
  61. // Add value 1 at key 1
  62. testTable.Add(1, 1);
  63. // Try to add another value 2 at key 1 (should be ignored)
  64. testTable.Add(1, 2);
  65. // And add another value 1 at key 2.
  66. testTable.Add(2, 1);
  67. // All values should be 1 now!
  68. foreach (int num in testTable.Values)
  69. {
  70. Assert.Equal(1, num);
  71. }
  72. }
  73. #endregion
  74. }
  75. }