I\'m trying to create an \"ordered\" cache of objects in C#, where the order is determined by how many times that has been accessed.
I\'ve looked into Dictionary, Sorted
The "Proper" way to do this is to implement IComparable (http://msdn.microsoft.com/en-us/library/system.icomparable.aspx) Interface in your MyCache Class.
This will expose a method called CompareTo which you will have to write in your code.
You would just create that method and put some logic in there that says if this object is greater, less than or equal to the object passed in.
Then you use it in your client code by saying int result = MyCache1.ComparTo(MyCache2);
The result will be -1 0 or 1 based on if its greater than less than or equal too.
Why not to use classic List and sort it, using sort method and write your own compare delagate ?
MyCache.Sort(delegate(Result a, Result b)
{
if (a.hits > b.hits) return -1;
if (a.hits < b.hits) return 1;
return 0;
});
If you need access by key, you can have 2 structures. One for fast access, second holding sorted data.
Dictionary<String, Result> accessMap;
List<Result> MyCache;
accessMap["Object 1"] = obj1;
MyCache.add(obj1);
accessMap[Object 1].Increase();
//sort MyCache
foreach(Result result in MyCache) {
Console.Write(result.Name + " - hits " + result.Hits);
}
Building upon your pseudo code, this seems to be working:
var MyCache = new Dictionary<string, Result>
{
{"My result 1", new Result("My result 1")},
{"My result 2", new Result("My result 2")},
{"My result 3", new Result("My result 3")},
{"My result 4", new Result("My result 4")}
};
MyCache["My result 2"].IncreaseHits();
MyCache["My result 2"].IncreaseHits();
MyCache["My result 3"].IncreaseHits();
foreach (var result in MyCache.OrderByDescending(x => x.Value.Hits))
{
Console.WriteLine(result.Value.Name + " - hits " + result.Value.Hits);
}