PageRenderTime 294ms CodeModel.GetById 141ms app.highlight 3ms RepoModel.GetById 148ms app.codeStats 0ms

/Utilities/Collections/UniqueChangeableList.cs

#
C# | 82 lines | 54 code | 5 blank | 23 comment | 6 complexity | b1675d20f88e6e033868e6cd804b084e MD5 | raw file
 1using System.Collections.Generic;
 2using Delta.Utilities.Helpers;
 3using NUnit.Framework;
 4
 5namespace Delta.Utilities.Collections
 6{
 7	/// <summary>
 8	/// Same as ChangeableList, which allows to add and remove elements
 9	/// while enumerating, but this also checks if elements do already
10	/// exists. It will not add duplicates, duplicates are ignored!
11	/// </summary>
12	public class UniqueChangeableList<T> : ChangeableList<T>
13	{
14		#region Add (Public)
15		/// <summary>
16		/// Add element, if it already exists, nothing will be added.
17		/// </summary>
18		/// <param name="item">Item</param>
19		public override void Add(T item)
20		{
21			if (base.IndexOf(item) < 0)
22			{
23				base.Add(item);
24			}
25		}
26		#endregion
27
28		#region AddRange (Public)
29		/// <summary>
30		/// Add range, will just use Add to add all elements.
31		/// </summary>
32		/// <param name="c">Collection</param>
33		public override void AddRange(ICollection<T> c)
34		{
35			foreach (T obj in c)
36			{
37				Add(obj);
38			}
39		}
40		#endregion
41	}
42
43	/// <summary>
44	/// UniqueChangeableList tests, needs to be an extra class because
45	/// nesting in generic classes is not supported by NUnit or xUnit.
46	/// </summary>
47	public class UniqueChangeableListTests
48	{
49		#region TestUniqueChangeableList (Static)
50		/// <summary>
51		/// Test UniqueChangeableList. Note: Too slow for a dynamic unit test.
52		/// </summary>
53		[Test]
54		public static void TestUniqueChangeableList()
55		{
56			UniqueChangeableList<int> list = new UniqueChangeableList<int>();
57			list.Add(2);
58			list.Add(3);
59			list.Add(4);
60			list.Add(2);
61			Assert.Equal("2, 3, 4", list.Write());
62
63			// Add element while enumerating (7) and remove a element (2)
64			foreach (int num in list)
65			{
66				//Console.WriteLine("Num: " + num);
67				if (num == 3)
68				{
69					list.Add(7);
70				}
71				else if (num == 2)
72				{
73					list.Remove(num);
74				}
75			}
76			// The resulting list should now have changed from "2, 3, 4" to "3, 4, 7"
77			Assert.Equal("3, 4, 7", list.Write());
78		}
79		#endregion
80	}
81}
82