Skip to content

Instantly share code, notes, and snippets.

@reidev275
Last active December 27, 2015 18:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reidev275/7373780 to your computer and use it in GitHub Desktop.
Save reidev275/7373780 to your computer and use it in GitHub Desktop.
IList<T> decorator holding a max number of items using FIFO
using System;
using System.Collections.Generic;
namespace Reid.Collections
{
public class MaxItemList<T> : IList<T>
{
readonly IList<T> _list;
readonly int _maxItems;
public MaxItemList(IList<T> list, int maximumItems)
{
if (list == null) throw new ArgumentNullException("list");
if (maximumItems <= 0) throw new ArgumentException("MaximumItems must be a positive integer");
_list = list;
_maxItems = maximumItems;
}
public bool Contains(T item)
{
return _list.Contains(item);
}
public void Add(T item)
{
if (item == null) throw new ArgumentNullException("item");
MakeSpace();
_list.Add(item);
}
public int IndexOf(T item)
{
return _list.IndexOf(item);
}
public void Insert(int index, T item)
{
MakeSpace();
_list.Insert(index, item);
}
public void RemoveAt(int index)
{
_list.RemoveAt(index);
}
public T this[int index]
{
get
{
return _list[index];
}
set
{
_list[index] = value;
}
}
public void Clear()
{
_list.Clear();
}
public void CopyTo(T[] array, int arrayIndex)
{
_list.CopyTo(array, arrayIndex);
}
public int Count
{
get { return _list.Count; }
}
public bool IsReadOnly
{
get { return _list.IsReadOnly; }
}
public bool Remove(T item)
{
return _list.Remove(item);
}
public IEnumerator<T> GetEnumerator()
{
return _list.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return _list.GetEnumerator();
}
void MakeSpace()
{
if (_list.Count == _maxItems) _list.Remove(_list[0]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment