106 lines
3.2 KiB
C#
106 lines
3.2 KiB
C#
using System;
|
|
using System.Collections;
|
|
using System.Collections.Generic;
|
|
|
|
namespace ln.objects.collections
|
|
{
|
|
public class LazyList<T> : IList<T> where T:class
|
|
{
|
|
ObjectStore objectStore;
|
|
List<ListItem> listItems = new List<ListItem>();
|
|
|
|
public LazyList(ObjectStore objectStore)
|
|
:this(objectStore, new Guid[0]) { }
|
|
|
|
public LazyList(ObjectStore objectStore,Guid[] initialItems)
|
|
{
|
|
this.objectStore = objectStore;
|
|
}
|
|
|
|
public T this[int index]
|
|
{
|
|
get
|
|
{
|
|
ListItem listItem = listItems[index];
|
|
if (Object.ReferenceEquals(null, listItem.Value))
|
|
{
|
|
if (Guid.Empty.Equals(listItem.UID))
|
|
return null;
|
|
|
|
listItem.Value = objectStore.LoadObject<T>(listItem.UID);
|
|
}
|
|
return listItem.Value;
|
|
}
|
|
set
|
|
{
|
|
ListItem listItem = listItems[index];
|
|
listItem.Value = value;
|
|
listItem.UID = Guid.Empty;
|
|
}
|
|
}
|
|
|
|
public int Count => listItems.Count;
|
|
public bool IsReadOnly => false;
|
|
|
|
public void Add(T item)=> listItems.Add(new ListItem() { Value = item });
|
|
public void Clear() => listItems.Clear();
|
|
public bool Contains(T item)
|
|
{
|
|
Guid uid = objectStore.GetObjectUID(item);
|
|
foreach (ListItem listItem in listItems)
|
|
if (listItem.UID.Equals(uid) || Object.ReferenceEquals(item, listItem.Value))
|
|
return true;
|
|
return false;
|
|
}
|
|
|
|
public void CopyTo(T[] array, int arrayIndex)
|
|
{
|
|
for (int i = 0; i < Count; i++)
|
|
array[i + arrayIndex] = this[i];
|
|
}
|
|
|
|
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
|
|
public IEnumerator<T> GetEnumerator()
|
|
{
|
|
for (int i = 0; i < Count; i++)
|
|
yield return this[i];
|
|
}
|
|
public int IndexOf(T item)
|
|
{
|
|
Guid uid = objectStore.GetObjectUID(item);
|
|
for (int i = 0; i < Count; i++)
|
|
{
|
|
ListItem listItem = listItems[i];
|
|
if (listItem.UID.Equals(uid) || Object.ReferenceEquals(item, listItem.Value))
|
|
return i;
|
|
}
|
|
return -1;
|
|
}
|
|
|
|
public void Insert(int index, T item) => listItems.Insert(index, new ListItem() { Value = item });
|
|
public bool Remove(T item)
|
|
{
|
|
Guid uid = objectStore.GetObjectUID(item);
|
|
for (int i = 0; i < Count; i++)
|
|
{
|
|
ListItem listItem = listItems[i];
|
|
if (listItem.UID.Equals(uid) || Object.ReferenceEquals(item, listItem.Value))
|
|
{
|
|
listItems.RemoveAt(i);
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
public void RemoveAt(int index) => listItems.RemoveAt(index);
|
|
|
|
class ListItem
|
|
{
|
|
public Guid UID; // Identifier of reference in objectStore
|
|
public T Value; // Loaded Reference
|
|
}
|
|
|
|
}
|
|
}
|