C# Sorted List by Value with Object

前端 未结 9 928
失恋的感觉
失恋的感觉 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:32

    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 accessMap;
    List 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);
    }
    

提交回复
热议问题