I understand that this is an old post, but I recently needed something similar, and thought that this implementation could help if someone wants to create a common sequence in which order items are stored (and also allows you to insert before and after any subject). I'm sure someone has more efficient ways to do this, but it does the trick.
public class Sequence<T> : ICollection<T>
{
private readonly SortedList<long, T> _baseList;
public Sequence()
{
this._baseList = new SortedList<long, T>();
}
public IEnumerator<T> GetEnumerator()
{
return this._baseList.Values.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
public void Add(T item)
{
this._baseList.Add(this._baseList.Count(), item);
}
public void AddAfter(T item, T newItem)
{
var currentIndex = this._baseList.IndexOfValue(item);
if (currentIndex == _baseList.Count())
{
this.Add(newItem);
}
else
{
var itemsToMove = new SortedList<long, T>();
var total = Count;
for (var i = currentIndex + 1; i < total; i++)
{
itemsToMove.Add(i, _baseList[i]);
_baseList.Remove(i);
}
this.Add(newItem);
foreach (var itemToMove in itemsToMove)
{
this.Add(itemToMove.Value);
}
}
}
public void AddBefore(T item, T newItem)
{
var currentIndex = this._baseList.IndexOfValue(item);
var itemsToMove = new SortedList<long, T>();
var total = Count;
for (var i = currentIndex; i < total; i++)
{
itemsToMove.Add(i, this._baseList[i]);
_baseList.Remove(i);
}
this.Add(newItem);
foreach (var itemToMove in itemsToMove.Values)
{
this.Add(itemToMove);
}
}
public void Clear()
{
this._baseList.Clear();
}
public bool Contains(T item)
{
return this._baseList.ContainsValue(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
this._baseList.Values.CopyTo(array, arrayIndex);
}
public bool Remove(T item)
{
try
{
this._baseList.RemoveAt(this._baseList.IndexOfValue(item));
return true;
}
catch
{
return false;
}
}
public int Count
{
get
{
return this._baseList.Count();
}
}
public bool IsReadOnly
{
get
{
return false;
}
}
}
source
share