C# Sorted List by Value with Object

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

    Do you want something like this.

    public class Result {
      public int Hits = 0;
      public string Name = "";
    
      public void IncreaseHits() {
        this.hits++;
      }
    
      public Result(String name) {
        this.name = name;
      }
    }
    
    class Program {
       public Dictionary MyCache; //what structure to use?
    
    
       public main() {
        MyCache.Add("My result 1", new Result("My result 1"));
        MyCache.Add("My result 2", new Result("My result 2"));
        MyCache.Add("My result 3", new Result("My result 3"));
    
        MyCache["My result 2"].IncreaseHits();
        MyCache["My result 2"].IncreaseHits();
        MyCache["My result 3"].IncreaseHits();
    
       foreach(Result result in MyCache.Values.OrderByDesc(x => x.Hits)) {
          Console.Write(result.Name + " - hits " + result.Hits);
       }
      }
    }
    

    Alternatively

    public class MyCacheClass {
    
       private Dictionary cache = new Dictionary();
    
       public void IncreaseHits(string name) {
          Result cached;
          if (!cache.TryGetValue(name, out cached)) {
            cached = cache.Add(new Result(name));
          }
          cached.IncreaseHits();
       }
    
       public string Add(string name) {
          // Need to block duplicates....
          cache.Add(name, new Result(name));
       }
    
       public IEnumerable SortDesc {
          get { return cache.Values.OrderByDesc(x => x.Hits); }
       }
    }
    
    
    class Program {
       MyCacheClass MyCache = new MyCacheClass();
    
       MyCache.Add("result1");
       MyCache.IncreaseHits("My result 2");
       MyCache.IncreaseHits("My result 2");
       MyCache.IncreaseHits("My result 3");
    
       foreach(Result result in MyCache.SorDesc) {
          Console.WriteLine(string.Format("{0} - hits {1}",result.Name,result.Hits);
       }
    }
    

提交回复
热议问题