PageRenderTime 82ms CodeModel.GetById 40ms app.highlight 3ms RepoModel.GetById 37ms app.codeStats 0ms

/Utilities/Collections/UniqueHashtable.cs

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