using System; using System.Collections; using System.Collections.Generic; namespace ln.types.odb { public class PersistentList : IList where T: IPersistent { private Dictionary persistentInstances = new Dictionary(); private List index = new List(); public ODB ODB { get; } public PersistentList(ODB odb) { ODB = odb; } public T this[int n] { get { Guid persistentID = index[n]; if (!persistentInstances.ContainsKey(persistentID)) persistentInstances[persistentID] = (T)ODB.LoadPersistent(persistentID); return persistentInstances[persistentID]; } set { if (value == null) index[n] = Guid.Empty; Guid persistenceID = value.GetPersistenceID(); persistentInstances[persistenceID] = value; index[n] = persistenceID; } } public int Count => index.Count; public bool IsReadOnly => false; public void Add(T item) { if (item == null) { index.Add(Guid.Empty); } else { Guid persistenceID = item.GetPersistenceID(); persistentInstances[persistenceID] = item; index.Add(persistenceID); } } public void Clear() { persistentInstances.Clear(); index.Clear(); } public bool Contains(T item) { Guid persistenceID = item.GetPersistenceID(); if (index.Contains(persistenceID)) return true; foreach (T mine in this) { if (mine.Equals(item)) return true; } return false; } public void CopyTo(T[] array, int arrayIndex) { foreach (T item in this) { array[arrayIndex] = this[arrayIndex]; arrayIndex++; } } public IEnumerator GetEnumerator() { return new PersistentListEnumerator(this); } public int IndexOf(T item) { Guid persistenceID = item == null ? Guid.Empty : item.GetPersistenceID(); int i = index.IndexOf(persistenceID); if (i < 0) { for (int n=0;n= 0) RemoveAt(ind); return ind >= 0; } public void RemoveAt(int _index) { Guid persistenceID = index[_index]; if (persistentInstances.ContainsKey(persistenceID)) persistentInstances.Remove(persistenceID); index.RemoveAt(_index); } IEnumerator IEnumerable.GetEnumerator() { return new PersistentListEnumerator(this); } class PersistentListEnumerator : IEnumerator { int currentIndex = -1; PersistentList persistentList; public PersistentListEnumerator(PersistentList persistentList) { this.persistentList = persistentList; } public T Current => persistentList[currentIndex]; object IEnumerator.Current => persistentList[currentIndex]; public void Dispose() { persistentList = null; } public bool MoveNext() { currentIndex++; return (currentIndex < persistentList.Count); } public void Reset() { currentIndex = -1; } } } }