(Updated to show the general list class) This is a class that can be used for a special list class that loops (loops to the first element) upon reaching the last element:
public class ListCycle<T> : IList<T> { int curIndex = -1; List<T> list; int nMax; public ListCycle(int n) { list = new List<T>(n); nMax = n; } /// <summary>returns the current index we are in the list</summary> public int CurIndex { get { return curIndex; } } public int IndexOf(T item) { return list.IndexOf(item); } public bool Contains(T item) { return list.Contains(item); } public int Count { get { return list.Count; } } public bool IsReadOnly { get { return false; } } public IEnumerator<T> GetEnumerator() { return list.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return list.GetEnumerator(); } public T this[int index] { get { return list[index]; } set { list[index] = value; } } public void Add(T item) { curIndex++; if (curIndex >= nMax) curIndex = 0; if (curIndex < list.Count) list[curIndex] = item; else list.Add(item); } public void Clear() { list.Clear(); curIndex = -1; } //other mehods/properties for IList ... public void Insert(int index, T item) { throw new NotImplementedException(); } public bool Remove(T item) { throw new NotImplementedException(); } public void RemoveAt(int index) { throw new NotImplementedException(); } public void CopyTo(T[] array, int arrayIndex) { throw new NotImplementedException(); } }
Use is easy:
var list = new ListCycle<int>(10); //fill the list for (int i = 0; i < 10; i++) { list.Add(i); } //now list is: // 0, 1, 2, 3, ... //add more items will start from first list.Add(100); //overrides first item list.Add(101); //overrides second item //now list is: // 100, 101, 2, 3, ...
source share