/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
- using System;
- using System.Collections;
- using NUnit.Framework;
-
- namespace Delta.Utilities.Collections
- {
- /// <summary>
- /// Exactly the same as the Hashtable, but adds only new key/value pairs
- /// if the key does not currently exists (the key is unique). This class
- /// also enforces KeyType and ValueType unlike Hashtable, which accepts
- /// all kind of objects.
- /// </summary>
- [Serializable]
- public class UniqueHashtable<TKeyType, TValueType> : Hashtable
- {
- #region Add (Public)
- /// <summary>
- /// Add new key/value pair, will not add if the key does already exists!
- /// </summary>
- /// <param name="key">Key</param>
- /// <param name="val">val</param>
- public void Add(TKeyType key, TValueType val)
- {
- if (!Contains(key))
- {
- base.Add(key, val);
- }
- }
- #endregion
-
- #region WriteKeys (Public)
- /// <summary>
- /// Write all keys into a string for output/debug/tracing/etc.
- /// </summary>
- /// <returns>Output string with all the values.</returns>
- public string WriteKeys()
- {
- string ret = "";
- foreach (object obj in Keys)
- {
- ret +=
- ret.Length == 0
- ? ""
- : ", " + obj;
- }
- return ret;
- }
- #endregion
- }
-
- /// <summary>
- /// Test unique hashtable
- /// </summary>
- internal class TestUniqueHashtableHelper
- {
- #region TestAddingData (Public)
- /// <summary>
- /// Test adding data
- /// </summary>
- [Test]
- public void TestAddingData()
- {
- UniqueHashtable<int, int> testTable = new UniqueHashtable<int, int>();
- // Add value 1 at key 1
- testTable.Add(1, 1);
- // Try to add another value 2 at key 1 (should be ignored)
- testTable.Add(1, 2);
- // And add another value 1 at key 2.
- testTable.Add(2, 1);
- // All values should be 1 now!
- foreach (int num in testTable.Values)
- {
- Assert.Equal(1, num);
- }
- }
- #endregion
- }
- }