Click here to Skip to main content
Click here to Skip to main content
Articles » Database » Database » ADO.NET » Downloads
 
Add your own
alternative version
Go to top

Light ORM Library for .NET

, 8 Oct 2010
This article is about the Light Object-Relational Mapping library.
using System;
using System.Collections.Generic;

namespace Light.Model
{
	/// <summary>
	/// Cache used by Dao objects.
	/// </summary>
	public class LRUCache<T>
	{
		private Dictionary<string, LinkedListNode<T>> dict;
		private LinkedList<T> list;
		private int size = 0;
		
		/// <summary>
		/// Creates a new instance.
		/// </summary>
		/// <param name="sz">maximum number of objects to store</param>
		public LRUCache(int sz)
		{
			size = sz < 10 ? 10 : sz;
			dict = new Dictionary<string, LinkedListNode<T>>(size);
			list = new LinkedList<T>();
		}
		
		/// <summary>
		/// Gets or sets the maximum number of objects to store.
		/// </summary>
		public int Size
		{
			get { return size; }
			set { size = value < 10 ? 10 : value; }
		}
		
		/// <summary>
		/// Stores the given object. Overwrites if key exists.
		/// </summary>
		/// <param name="key">key under which to store given object</param>
		/// <param name="item">object to store</param>
		public void Put(string key, T item)
		{
			LinkedListNode<T> node;
			if(dict.TryGetValue(key, out node))
			{
				list.Remove(node);
				node = new LinkedListNode<T>(item);
				dict[key] = node;
				list.AddFirst(node);
			}
			else
			{
				if(list.Count == size)
					list.RemoveLast();
				node = new LinkedListNode<T>(item);
				dict[key] = node;
				list.AddFirst(node);
			}
		}
		
		/// <summary>
		/// Returns an object associated with given key.
		/// </summary>
		/// <param name="key">key under which an object was previously stored</param>
		/// <returns>object or null if key is not found</returns>
		public T Get(string key)
		{
			LinkedListNode<T> node;
			if(dict.TryGetValue(key, out node))
			{
				list.Remove(node);
				list.AddFirst(node);
				return node.Value;
			}
			return default(T);
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Sergey Busel
Software Developer (Senior)
United States United States
No Biography provided

| Advertise | Privacy | Mobile
Web03 | 2.8.140916.1 | Last Updated 8 Oct 2010
Article Copyright 2007 by Sergey Busel
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid