Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does .NET have a simple way to do overflow lists?

I'm looking to add a "recently opened" functionality to my application, and was wondering if there was a simple built in way to do lists that "overflow". By this I mean, when you add an element beyond the capacity of the list, all the items are shifted.

Code example of desired functionality (obviously its not true, the list would actually contain A,B,C):

List<string> list = new List<string>();

//if Overflow was 2

list.Add("A");
list.Add("B");
//List now contains A,B
list.Add("C");
//List now contains B,C

Sorry for the simple question. The problem itself is obvious to solve (intail plan was to inherit from List), I just don't like having to re-invent the wheel and confuse future programmers with custom objects when the language or framework has that functionality.

like image 649
James Avatar asked Nov 25 '11 20:11

James


People also ask

Which list is faster in C#?

BinarySearch will be faster than List<T>.

Can you add a list to a list C#?

Use the AddRange() method to append a second list to an existing list. list1. AddRange(list2);

What is stack overflow error in c#?

A StackOverflowException is thrown when the execution stack overflows because it contains too many nested method calls. For example, suppose you have an app as follows: C# Copy. using System; namespace temp { class Program { static void Main(string[] args) { Main(args); // Oops, this recursion won't stop. } } }


2 Answers

As far as I know ther is no such collection in the library.
You can write this very easily, based on a List<> or an array.

// untested
class OverFlowList<T>
{
    T[] _data;
    int _next = 0;

    public OferflowList(int limit)
    {
        _data = new T[limit];
    }

    void Add(T item)
    {
        _data[_next] = item;
        _next = (_next + 1) % _data.Length;
    }    
}
like image 98
Henk Holterman Avatar answered Sep 22 '22 00:09

Henk Holterman


You can do this easily with LinkedList<T>:

LinkedList<string> list = new LinkedList<string>();

//if Overflow was 2
list.AddFirst("A");
list.AddFirst("B");
list.AddFirst("C");
list.RemoveLast();

I would, personally, wrap this into a class that you could use, ie:

public class OverflowCollection<T> : IEnumerable<T>
{
    private int max;
    private LinkedList<T> list = new LinkedList<T>();

    public OverflowCollection(int maxItems)
    {
        this.max = maxItems;
    }

    public void Add(T item)
    {
        this.list.AddFirst(item);
        if (this.list.Count > max)
           this.list.RemoveLast();
    }

    // Implement IEnumerable<T> by returning list's enumerator...
}

This provides a very simple method, which has some nice advantages, including being able to change the overload amount at runtime, etc..

like image 28
Reed Copsey Avatar answered Sep 22 '22 00:09

Reed Copsey