/Utilities/Collections/UniqueChangeableList.cs
C# | 82 lines | 54 code | 5 blank | 23 comment | 6 complexity | b1675d20f88e6e033868e6cd804b084e MD5 | raw file
Possible License(s): Apache-2.0
- using System.Collections.Generic;
- using Delta.Utilities.Helpers;
- using NUnit.Framework;
-
- namespace Delta.Utilities.Collections
- {
- /// <summary>
- /// Same as ChangeableList, which allows to add and remove elements
- /// while enumerating, but this also checks if elements do already
- /// exists. It will not add duplicates, duplicates are ignored!
- /// </summary>
- public class UniqueChangeableList<T> : ChangeableList<T>
- {
- #region Add (Public)
- /// <summary>
- /// Add element, if it already exists, nothing will be added.
- /// </summary>
- /// <param name="item">Item</param>
- public override void Add(T item)
- {
- if (base.IndexOf(item) < 0)
- {
- base.Add(item);
- }
- }
- #endregion
-
- #region AddRange (Public)
- /// <summary>
- /// Add range, will just use Add to add all elements.
- /// </summary>
- /// <param name="c">Collection</param>
- public override void AddRange(ICollection<T> c)
- {
- foreach (T obj in c)
- {
- Add(obj);
- }
- }
- #endregion
- }
-
- /// <summary>
- /// UniqueChangeableList tests, needs to be an extra class because
- /// nesting in generic classes is not supported by NUnit or xUnit.
- /// </summary>
- public class UniqueChangeableListTests
- {
- #region TestUniqueChangeableList (Static)
- /// <summary>
- /// Test UniqueChangeableList. Note: Too slow for a dynamic unit test.
- /// </summary>
- [Test]
- public static void TestUniqueChangeableList()
- {
- UniqueChangeableList<int> list = new UniqueChangeableList<int>();
- list.Add(2);
- list.Add(3);
- list.Add(4);
- list.Add(2);
- Assert.Equal("2, 3, 4", list.Write());
-
- // Add element while enumerating (7) and remove a element (2)
- foreach (int num in list)
- {
- //Console.WriteLine("Num: " + num);
- if (num == 3)
- {
- list.Add(7);
- }
- else if (num == 2)
- {
- list.Remove(num);
- }
- }
- // The resulting list should now have changed from "2, 3, 4" to "3, 4, 7"
- Assert.Equal("3, 4, 7", list.Write());
- }
- #endregion
- }
- }
-