How to rewrite the list?

I need a collection that looks like a list, instead of always adding items when it reaches a certain length, it should start overwriting the values ​​from the first index and continue in a circular manner.

those. to limit 4 items:

specialList.Add(100); // {100} specialList.Add(101); // {100, 101} specialList.Add(102); // {100, 101, 102} specialList.Add(103); // {100, 101, 102, 103} specialList.Add(104); // {104, 101, 102, 103} specialList.Add(105); // {104, 105, 102, 103} 
+6
source share
2 answers

Instead of overwriting list , why not just clear your list and then start adding items.

Remove list using the following method

myList.Clear();

and then add items to list

myList.add(item);

EDIT

If you want to keep the old values, then after the list is filled with 10 elements, now to add an element, first the index

myList[0] = (newItem);

this newItem overwrite the first item in list

+4
source

(Updated to show the general list class) This is a class that can be used for a special list class that loops (loops to the first element) upon reaching the last element:

 public class ListCycle<T> : IList<T> { int curIndex = -1; List<T> list; int nMax; public ListCycle(int n) { list = new List<T>(n); nMax = n; } /// <summary>returns the current index we are in the list</summary> public int CurIndex { get { return curIndex; } } public int IndexOf(T item) { return list.IndexOf(item); } public bool Contains(T item) { return list.Contains(item); } public int Count { get { return list.Count; } } public bool IsReadOnly { get { return false; } } public IEnumerator<T> GetEnumerator() { return list.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return list.GetEnumerator(); } public T this[int index] { get { return list[index]; } set { list[index] = value; } } public void Add(T item) { curIndex++; if (curIndex >= nMax) curIndex = 0; if (curIndex < list.Count) list[curIndex] = item; else list.Add(item); } public void Clear() { list.Clear(); curIndex = -1; } //other mehods/properties for IList ... public void Insert(int index, T item) { throw new NotImplementedException(); } public bool Remove(T item) { throw new NotImplementedException(); } public void RemoveAt(int index) { throw new NotImplementedException(); } public void CopyTo(T[] array, int arrayIndex) { throw new NotImplementedException(); } } 

Use is easy:

 var list = new ListCycle<int>(10); //fill the list for (int i = 0; i < 10; i++) { list.Add(i); } //now list is: // 0, 1, 2, 3, ... //add more items will start from first list.Add(100); //overrides first item list.Add(101); //overrides second item //now list is: // 100, 101, 2, 3, ... 
+5
source

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


All Articles