Syed Umar Anis.NetCustom .Net (C#) Collection: Recently Used List
Syed Umar Anis.NetCustom .Net (C#) Collection: Recently Used List

I came across a situation where I needed a collection which can hold recently used objects of a particular kind. For instance, recently opened files, recently used fonts or colors etc. Such a list should demonstrate following behavior:

  • List should have a limited size (or call it maximum size). As list grows beyond the maximum size, the oldest item should be dropped.
  • Newly added items should be inserted at the top of the list i.e. index 0.
  • If an item to be added already exists in the list, it should be moved to the top of the list (at index 0) rather than being duplicated. This means that entries in the list will always be unique and order of the items will follow how recently they were used.

Following custom collection class provides this functionality:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyNamespace
{
    
    public class RecentlyUsedList<T>
    {
        
        public RecentlyUsedList(int maxSize)
        {
            this.maxSize = maxSize;
        }

        private List<T> list = new List<T>();

        public T this[int i]
        {
            get
            {
                return list[i];
            }            
        }

        private int maxSize;

        public int MaxSize
        {
            get
            {
                return maxSize;
            }                      
        }

        public int Count
        {
            get
            {
                return list.Count;
            }
        }

        public void Add(T item)
        {
            int i = list.IndexOf(item);
            if (i != -1)    list.RemoveAt(i);

            if (list.Count == MaxSize) list.RemoveAt(list.Count - 1);

            list.Insert(0, item);
        }
    
    }
}

One nice enhancement to the class would be to implement System.Collections.IEnumerable interface. It will enable the collection to be iterated using foreach loop.

Hi, I’m Umar

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *