Click here to Skip to main content
15,881,882 members
Articles / Database Development / SQL Server

Light ORM Library for .NET

Rate me:
Please Sign up or sign in to vote.
4.83/5 (39 votes)
8 Oct 2010CPOL17 min read 220.4K   3.1K   184  
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)


Written By
Software Developer (Senior)
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions