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.
BinarySearch will be faster than List<T>.
Use the AddRange() method to append a second list to an existing list. list1. AddRange(list2);
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. } } }
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;
}
}
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..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With