-
Notifications
You must be signed in to change notification settings - Fork 0
/
ObservableCollection{TValue}.cs
75 lines (59 loc) · 2.21 KB
/
ObservableCollection{TValue}.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
* ObservableCollection{TValue}.cs
*
* Created: 2023-02-01-03:58:10
* Modified: 2023-02-01-03:58:10
*
* Author: David G. Mooore, Jr. <david@dgmjr.io>
*
* Copyright © 2022-2023 David G. Mooore, Jr., All Rights Reserved
* License: MIT (https://opensource.org/licenses/MIT)
*/
namespace System.Collections.Generic;
public class ObservableCollection<TValue> : ICollection<TValue>
{
private Action<TValue> _onAdd = v => { };
private Action<TValue> _onRemove = v => { };
private readonly List<TValue> _list = new();
public virtual void OnAdd(TValue value) => _onAdd?.Invoke(value);
public virtual void OnRemove(TValue value) => _onRemove?.Invoke(value);
public ObservableCollection() : this(Empty<TValue>(), v => { }, v => { }) { }
public ObservableCollection(Action<TValue>? onAdd = null, Action<TValue>? onRemove = null) : this(Empty<TValue>(), onAdd, onRemove) { }
public virtual void Clear()
{
foreach (var item in _list)
OnRemove(item);
_list.Clear();
}
public virtual bool Contains(TValue item) => _list.Contains(item);
public virtual void CopyTo(TValue[] array, int arrayIndex) => _list.CopyTo(array, arrayIndex);
public virtual bool Remove(TValue item)
{
var result = _list.Remove(item);
if (result)
OnRemove(item);
return result;
}
public virtual IEnumerator<TValue> GetEnumerator() => _list.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public virtual void Add(TValue item)
{
_list.Add(item);
OnAdd(item);
}
public virtual int Count => _list.Count;
public virtual bool IsReadOnly => false;
public virtual int IndexOf(TValue item) => _list.IndexOf(item);
public virtual void Insert(int index, TValue item)
{
_list.Insert(index, item);
OnAdd(item);
}
public ObservableCollection(IEnumerable<TValue> collection, Action<TValue>? onAdd = null, Action<TValue>? onRemove = null)
{
_onAdd ??= onAdd;
_onRemove ??= onRemove;
foreach (var item in collection)
Add(item);
}
}