using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TimetableDesigner.Customs.Collections { public class ObservableDictionary : ObservableCollection>, IDictionary { #region PROPERTIES public ICollection Keys => Items.Select(p => p.Key).ToList(); public ICollection Values => Items.Select(p => p.Value).ToList(); public bool IsReadOnly => false; #endregion #region INDEXERS public TValue this[TKey key] { get { if (!TryGetValue(key, out TValue result)) { throw new ArgumentException("Key not found"); } return result; } set { if (ContainsKey(key)) { GetKeyValuePairByTheKey(key).Value = value; } else { Add(key, value); } } } #endregion #region CONSTRUCTORS public ObservableDictionary() : base() { } public ObservableDictionary(IDictionary dictionary) : base() { foreach (KeyValuePair pair in dictionary) { this.Add(pair); } } #endregion #region PUBLIC METHODS public void Add(TKey key, TValue value) { if (ContainsKey(key)) { throw new ArgumentException("The dictionary already contains the key"); } Add(new ObservableKeyValuePair(key, value)); } public void Add(KeyValuePair item) => Add(item.Key, item.Value); public bool Contains(KeyValuePair item) { ObservableKeyValuePair pair = GetKeyValuePairByTheKey(item.Key); if (Equals(pair, default(ObservableKeyValuePair))) { return false; } return Equals(pair.Value, item.Value); } public bool ContainsKey(TKey key) { ObservableKeyValuePair pair = ((ObservableCollection>)this).FirstOrDefault((i) => Equals(key, i.Key)); return !Equals(default(ObservableKeyValuePair), pair); } public void CopyTo(KeyValuePair[] array, int arrayIndex) { throw new NotImplementedException(); } public bool Remove(TKey key) { List> remove = ((ObservableCollection>)this).Where(pair => Equals(key, pair.Key)).ToList(); foreach (ObservableKeyValuePair pair in remove) { Remove(pair); } return remove.Count > 0; } public bool Remove(KeyValuePair item) { ObservableKeyValuePair pair = GetKeyValuePairByTheKey(item.Key); if (Equals(pair, default(ObservableKeyValuePair))) { return false; } if (!Equals(pair.Value, item.Value)) { return false; } return Remove(pair); } public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) { value = default; var pair = GetKeyValuePairByTheKey(key); if (Equals(pair, default(ObservableKeyValuePair))) { return false; } value = pair.Value; return true; } IEnumerator> IEnumerable>.GetEnumerator() => ((ObservableCollection>)this).Select(i => new KeyValuePair(i.Key, i.Value)).GetEnumerator(); #endregion #region PRIVATE METHODS private ObservableKeyValuePair GetKeyValuePairByTheKey(TKey key) => ((ObservableCollection>)this).FirstOrDefault(i => i.Key.Equals(key)); #endregion } }