C# Sorted List by Value with Object

前端 未结 9 1056
失恋的感觉
失恋的感觉 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条回答
  •  遇见更好的自我
    2021-01-21 20:31

    I guess you need something like:

    SortedDictionary MyCache = new SortedDictionary();
    string strKey = "NewResult";
    if (MyCache.ContainsKey(strKey))
    {
        MyCache[strKey] = MyCache[strKey] + 1;
    }
    else
    {
        MyCache.Add(strKey, 1);
    }
    

    But SortedDictionary is sorted on the key

    SortedDictionary - MSDN

    Represents a collection of key/value pairs that are sorted on the key.

    You can extract the dictionary to List> and then sort them based on teh value like:

    List> list = MyCache.ToList();
    foreach (var item in list.OrderByDescending(r=> r.Value))
    {
        Console.WriteLine(item.Key+ " - hits " + item.Value);
    } 
    

    So you can have:

    class Program
    {
        public static SortedDictionary MyCache = new SortedDictionary();
        static void Main(string[] args)
        {
    
            AddToDictionary("Result1");
            AddToDictionary("Result1");
            AddToDictionary("Result2");
            AddToDictionary("Result2");
            AddToDictionary("Result2");
            AddToDictionary("Result3");
    
            List> list = MyCache.ToList();
            foreach (var item in list.OrderByDescending(r=> r.Value))
            {
                Console.WriteLine(item.Key+ " - hits " + item.Value);
            } 
    
    
        }
        public static void AddToDictionary(string strKey)
        {
            if (MyCache.ContainsKey(strKey))
            {
                MyCache[strKey] = MyCache[strKey] + 1;
            }
            else
            {
                MyCache.Add(strKey, 1);
            }
        }
    }
    

    Then the output would be:

    Result2 - hits 3
    Result1 - hits 2
    Result3 - hits 1
    

提交回复
热议问题