Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// <summary>
- /// A List restricted to contain a limited number of items.
- /// When the list is full an item is added the oldest
- /// </summary>
- /// <typeparam name="T"></typeparam>
- public class ListBounded<T>
- {
- #region prop
- //private T[] _array;
- // 'internal' for testing purposes only
- internal T[] _array;
- private int _max;
- private int _head;
- // Is true if more items than _max were added to the list.
- private bool _firstRoundDone = false;
- /// <summary>
- /// Number of available items in the list
- /// </summary>
- public int Count
- {
- get
- {
- return _firstRoundDone ? _max : _head + 1;
- }
- }
- /// <summary>
- /// Oldest item added to the list
- /// </summary>
- public T First
- {
- get
- {
- if (_head < 0)
- throw new IndexOutOfRangeException("The list is empty");
- if (_firstRoundDone)
- return _array[(_head + 1) % _max];
- else
- return _array[0];
- }
- }
- /// <summary>
- /// Last item added to the list
- /// </summary>
- public T Last
- {
- get
- {
- if (_head < 0)
- throw new IndexOutOfRangeException("The list is empty");
- return _array[_head];
- }
- }
- #endregion
- #region init
- public ListBounded(int maxItem)
- {
- _max = maxItem;
- Clear();
- }
- #endregion
- #region core
- public void Clear()
- {
- _array = new T[_max];
- _head = -1;
- }
- public void Add(T item)
- {
- if (_head == _max - 1) _firstRoundDone = true;
- _head = (_head + 1) % _max;
- _array[_head] = item;
- }
- public List<T> ToList()
- {
- var list = new List<T>();
- lock (this)
- {
- int count = this.Count;
- for (int i = 0; i < count; i++)
- {
- list.Add(_array[(_head + i) % count]);
- }
- }
- return list;
- }
- #endregion
- }
Advertisement
Add Comment
Please, Sign In to add comment