C# Sorted List by Value with Object

前端 未结 9 1015
失恋的感觉
失恋的感觉 2021-01-21 20:06

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

9条回答
  •  萌比男神i
    2021-01-21 20:24

    When I needed something like this, I created what I called an MruDictionary. It consisted of a LinkedList, and a Dictionary> (where T is the type of object, and the object key was type string).

    Access is through the dictionary. When an item is accessed, it is moved to the head of the list. When an item is added, it's added to the head of the list. If the list size grows beyond the set maximum, the last node in the list is removed.

    This worked very well. The items weren't kept in order by number of times used, but rather in strict MRU order. This typically kept the most often used items in the cache, but if there was a long period in which a popular item wasn't used, it would get flushed. For my purposes this worked very well.

    I wrote an article about it. Full source with description is available at http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=626.

    It should be easy enough to add the hit count if you really need it.

提交回复
热议问题