Created
October 14, 2013 21:11
-
-
Save reidev275/6982274 to your computer and use it in GitHub Desktop.
simple List with max item count and age out capability
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Timed<T> | |
{ | |
readonly DateTime _time; | |
readonly T _item; | |
public Timed(T item) | |
{ | |
if (item == null) throw new ArgumentNullException("item"); | |
_item = item; | |
} | |
public T Item { get { return _item; } } | |
public DateTime Time { get { return _time; } } | |
public double AgeInMinutes() | |
{ | |
return (DateTime.UtcNow - _time).TotalMinutes; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class TimedMaxItemList<T> | |
{ | |
readonly List<Timed<T>> _list = new List<Timed<T>>(); | |
readonly int _timeoutMinutes; | |
readonly int _maximumItems; | |
readonly EqualityComparer<T> @default = EqualityComparer<T>.Default; | |
public TimedMaxItemList(int minutesToTimeout, int maximumItems) | |
{ | |
_timeoutMinutes = minutesToTimeout; | |
_maximumItems = maximumItems; | |
} | |
public bool Contains(T item) | |
{ | |
RemoveOldItems(); | |
for (int i = 0; i < _list.Count; i++) | |
{ | |
if (@default.Equals(_list[i].Item, item)) return true; | |
} | |
return false; | |
} | |
public void Add(T item) | |
{ | |
if (item == null) throw new ArgumentNullException("item"); | |
MakeSpace(); | |
_list.Add(new Timed<T>(item)); | |
} | |
void RemoveOldItems() | |
{ | |
_list.RemoveAll(x => x.AgeInMinutes() > _timeoutMinutes); | |
} | |
void MakeSpace() | |
{ | |
if (_list.Count == _maximumItems) | |
{ | |
_list.Remove(_list.OrderBy(x => x.Time).First()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment