Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List with limited item

I need to keep a short history of values. So I need a list with a maximum number of items. And I want it to accept new addition even when it's full. In that case I want the oldest item I added to be lost. I did not find any class suiting this purpose then did my own. I will certainly add methods later on but for now I have what I need.

So my first question to you is: Is it a correct code: http://pastebin.com/0BCbyNqJ Does that class look clean enough to you?

And my second question is about these exceptions I am throwing.

/// <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];
    }
}

Before anything is added to my list, I would like calls to First, Last and Countto return null. I think that would make more sense. But I don't know how to do so since the return types are int or T, for which I don't want to add a constraint like where T:Nullable. As I don't see any solution I wonder if the Exception is not, afterall, the most elegant way. Or should I implement methods like GetFirst(out T first) or even TryGetFirst(out T)?

like image 496
Mr.Pe Avatar asked Dec 01 '22 23:12

Mr.Pe


2 Answers

Extending Queue<> would produce a very short code, like this:

public class Buffer<T> : Queue<T>
{
    private int? maxCapacity { get; set; }

    public Buffer() { maxCapacity = null; }
    public Buffer(int capacity) { maxCapacity = capacity; }

    public void Add(T newElement)
    {
        if (this.Count == (maxCapacity ?? -1)) this.Dequeue(); // no limit if maxCapacity = null
        this.Enqueue(newElement);
    }
}

.Clear() and .ToList() would be inherited, no need to implement them.

like image 176
Alex Avatar answered Dec 05 '22 08:12

Alex


Consider publicly available LRU caches such as http://code.google.com/p/csharp-lru-cache/.

like image 24
akton Avatar answered Dec 05 '22 10:12

akton