Is there a specific collection type in .NET which allows storing a limited number objects and removing the oldest element automatically? What's the easiest way to implement such "Recent Files" functionality?
+3
A:
You might want to try System.Collections.Queue?
Each time before you add an object to your Queue (Enqueue()
), you can check the Count
to decide if you need the oldest object to be removed (Dequeue()
).
Lee Sy En
2010-10-03 16:35:56
Of course you should use Queue<>.
Hans Passant
2010-10-03 17:12:06
+1
A:
You are probably interested in an LRU cache implementation, since a Queue won't give you the easy lookup ability.
EDIT: For just offering "Recent Files" functionality LRU cache would be overkill - go with the simple Queue just like the other poster suggested.
BrokenGlass
2010-10-03 16:41:12
+2
A:
I would go with a class wrapping a linked list. For a quick and dirty example for a starting point see the code below. Of course you will want to add other accessors etc. This will give you the ability to move recently accessed items to the head of the list etc.
public class RecentList<T> : IEnumerable<T>
{
private LinkedList<T> _list = new LinkedList<T>();
private int _maxItems;
public RecentList(int maxItems)
{
_maxItems = maxItems;
}
public void Add(T item)
{
_list.AddFirst(item);
if (_list.Count > _maxItems)
{
_list.RemoveLast();
}
}
public IEnumerator<T> GetEnumerator()
{
return _list.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _list.GetEnumerator();
}
}
Chris Taylor
2010-10-03 16:54:35
+1 This will work perfectly fine if you don't need random access. The alternative is to implement a queue with a fixed size which just increment head (and tail to sync.) even if it is full.
lasseespeholt
2010-10-03 18:00:24