FluentList.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. namespace InABox.Core
  5. {
  6. public class FluentList<T> : IEnumerable<T>
  7. {
  8. public delegate void FluentListChangedEvent(object sender, EventArgs args);
  9. private bool _enabled = true;
  10. private readonly List<T> _values = new List<T>();
  11. public bool Enabled
  12. {
  13. get => _enabled;
  14. set
  15. {
  16. if (value)
  17. EndUpdate();
  18. else
  19. BeginUpdate();
  20. }
  21. }
  22. public T this[int i]
  23. {
  24. get => _values[i];
  25. set
  26. {
  27. _values[i] = value;
  28. Changed();
  29. }
  30. }
  31. public int Count => _values.Count;
  32. public IEnumerator<T> GetEnumerator()
  33. {
  34. return ((IEnumerable<T>)_values).GetEnumerator();
  35. }
  36. IEnumerator IEnumerable.GetEnumerator()
  37. {
  38. return ((IEnumerable<T>)_values).GetEnumerator();
  39. }
  40. public FluentList<T> Add(T value)
  41. {
  42. if (!_values.Contains(value))
  43. _values.Add(value);
  44. return Changed();
  45. }
  46. public FluentList<T> AddRange(params T[] values)
  47. {
  48. foreach (var value in values)
  49. if (!_values.Contains(value))
  50. _values.Add(value);
  51. return Changed();
  52. }
  53. public FluentList<T> AddRange(IEnumerable<T> values)
  54. {
  55. foreach (var value in values)
  56. if (!_values.Contains(value))
  57. _values.Add(value);
  58. return Changed();
  59. }
  60. public FluentList<T> Remove(T value)
  61. {
  62. if (_values.Contains(value))
  63. _values.Remove(value);
  64. return Changed();
  65. }
  66. public FluentList<T> RemoveAt(int index)
  67. {
  68. if (index > 0 && index < _values.Count)
  69. _values.RemoveAt(index);
  70. return Changed();
  71. }
  72. public FluentList<T> Clear()
  73. {
  74. _values.Clear();
  75. return Changed();
  76. }
  77. public event FluentListChangedEvent OnChanged;
  78. public FluentList<T> BeginUpdate()
  79. {
  80. _enabled = false;
  81. return this;
  82. }
  83. private FluentList<T> Changed()
  84. {
  85. if (_enabled)
  86. OnChanged?.Invoke(this, new EventArgs());
  87. return this;
  88. }
  89. public FluentList<T> EndUpdate()
  90. {
  91. _enabled = true;
  92. return Changed();
  93. }
  94. }
  95. }