PageRenderTime 50ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

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