Skip to content

Instantly share code, notes, and snippets.

@taljacob2
Last active October 21, 2024 06:19
Show Gist options
  • Save taljacob2/f36481bccd3885e2374649430c26a928 to your computer and use it in GitHub Desktop.
Save taljacob2/f36481bccd3885e2374649430c26a928 to your computer and use it in GitHub Desktop.
RotatingList Demo
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Linq;
public class Program
{
public static void Main()
{
RotatingList<double> rotatingList = new() { 1, 2, 3 };
Console.WriteLine(string.Join(", ", rotatingList));
rotatingList.Add(4);
Console.WriteLine(string.Join(", ", rotatingList));
rotatingList.Add(5);
Console.WriteLine(string.Join(", ", rotatingList));
}
}
public class RotatingList<T> : ICollection<T>, IEnumerable<T>, IEnumerable, IReadOnlyCollection<T>, ICollection, IDeserializationCallback, ISerializable
{
private readonly LinkedList<T> m_LinkedList = new();
private readonly uint m_MaxSize;
public int Count => ((ICollection<T>)m_LinkedList).Count;
public bool IsReadOnly => ((ICollection<T>)m_LinkedList).IsReadOnly;
public bool IsSynchronized => ((ICollection)m_LinkedList).IsSynchronized;
public object SyncRoot => ((ICollection)m_LinkedList).SyncRoot;
public RotatingList(uint maxSize = 3)
{
m_MaxSize = maxSize;
}
private void RemoveLastAndAddFirst(T elementToAdd)
{
if (m_LinkedList.Count >= m_MaxSize) { m_LinkedList.RemoveLast(); }
m_LinkedList.AddFirst(elementToAdd);
}
public void Add(T element)
{
RemoveLastAndAddFirst(element);
}
public T? GetNewestElementOrDefault()
{
return m_LinkedList.FirstOrDefault();
}
public T? GetOldestElementOrDefault()
{
return m_LinkedList.LastOrDefault();
}
public T GetNewestElement()
{
return m_LinkedList.First();
}
public T GetOldestElement()
{
return m_LinkedList.Last();
}
public void Clear()
{
((ICollection<T>)m_LinkedList).Clear();
}
public bool Contains(T item)
{
return ((ICollection<T>)m_LinkedList).Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
((ICollection<T>)m_LinkedList).CopyTo(array, arrayIndex);
}
public bool Remove(T item)
{
return ((ICollection<T>)m_LinkedList).Remove(item);
}
public IEnumerator<T> GetEnumerator()
{
return ((IEnumerable<T>)m_LinkedList).GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return ((System.Collections.IEnumerable)m_LinkedList).GetEnumerator();
}
public void CopyTo(Array array, int index)
{
((ICollection)m_LinkedList).CopyTo(array, index);
}
public void OnDeserialization(object? sender)
{
((IDeserializationCallback)m_LinkedList).OnDeserialization(sender);
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
((ISerializable)m_LinkedList).GetObjectData(info, context);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment