Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - finite list or limited list?

Tags:

c#

I am wondering about a certain functionality in C#...

I would like to have a List<Object> MyList();, which I could .Add(new Object()) finite amount of times. Let's say I added 5 items, and if I would add sixth, then the last item would be destroyed, and this sixth element would be put on top of the list.

Is there any built-in mechanism in c# that does that?

like image 754
ojek Avatar asked Jan 22 '26 11:01

ojek


1 Answers

There is no build-in collection in Framework as Servy said. However, you can make a CircularBuffer like this -

enter image description here

namespace DataStructures
{
    class Program
    {
        static void Main(string[] args)
        {
            var buffer = new CircularBuffer<int>(capacity: 3);

            while (true)
            {
                int value;
                var input = Console.ReadLine();

                if (int.TryParse(input, out value))
                {
                    buffer.Write(value);
                    continue;
                }
                break;
            }

            Console.WriteLine("Buffer: ");
            while (!buffer.IsEmpty)
            {
                Console.WriteLine(buffer.Read());
            }
            Console.ReadLine();
        }
    }
}

namespace DataStructures
{
    public class CircularBuffer<T>
    {
        private T[] _buffer;
        private int _start;
        private int _end;

        public CircularBuffer()
            : this(capacity: 3)
        {
        }

        public CircularBuffer(int capacity)
        {
            _buffer = new T[capacity + 1];
            _start = 0;
            _end = 0;
        }

        public void Write(T value)
        {
            _buffer[_end] = value;
            _end = (_end + 1) % _buffer.Length;
            if (_end == _start)
            {
                _start = (_start + 1) % _buffer.Length;
            }
        }

        public T Read()
        {
            T result = _buffer[_start];
            _start = (_start + 1) % _buffer.Length;
            return result;
        }

        public int Capacity
        {
            get { return _buffer.Length; }
        }

        public bool IsEmpty
        {
            get { return _end == _start; }
        }

        public bool IsFull
        {
            get { return (_end + 1) % _buffer.Length == _start; }
        }
    }
}

Above code is from PluralSight - Scott Allen's C# Generics.

like image 137
Win Avatar answered Jan 25 '26 02:01

Win



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!