Does .NET have an easy way to do overflow lists?

I want to add “recently opened” functionality to my application and wondered if there was a simple built-in way to make lists that are “overflowing”. By this, I mean that when you add an item outside the scope of the list, all items are shifted.

An example code of the desired functionality (obviously this is not so, the list actually contains 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 (the inheritance plan was inherited from List), I just don’t like to reinvent the wheel and confuse future programmers with user objects when the language or infrastructure has this functionality.

+6
source share
3 answers

As far as I know, the library does not have such a collection.
You can write this very easily based on 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; } } 
+5
source

You can do this easily using 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 put it in a class that you could use, for example:

 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 enumerator... } 

This provides a very simple method that has some nice advantages, including the ability to change the amount of congestion at runtime, etc.

+4
source

Use a special class that implements IList , then when the Add tool checks your constraint and executes it.

0
source

Source: https://habr.com/ru/post/902414/


All Articles