我有一个像TDictionary<String,Integer>这样声明的TDictionary,现在我想获取存储在TDictionary中的最大值。我可以在TDictionary上进行迭代并比较值,但是我想知道是否存在更好的方法? exist any function or maybe the dictionary can be sorted by the values to retrieve the max value stored?
这就是我现在正在做的

var
   MyDict       : TDictionary<String,Integer>;
   MaxValue, i  : Integer;
begin
   MyDict:=TDictionary<String,Integer>.Create;
   try
     MyDict.Add('this',1);
     MyDict.Add('is',7);
     MyDict.Add('a',899);
     MyDict.Add('sample',1000);
     MyDict.Add('finding',12);
     MyDict.Add('the',94);
     MyDict.Add('max',569);
     MyDict.Add('value',991);

     MaxValue:=MyDict.ToArray[0].Value;
     for i in MyDict.Values do
      if i>MaxValue then MaxValue:=i;

     ShowMessage(Format('The max value is %d',[MaxValue]));
   finally
     MyDict.Free;
   end;
end;

最佳答案

您是否要删除项目或减少项目数量?如果不是,则可以考虑创建TDictionary的新后代,在其中重写Add()方法并跟踪迄今为止添加的最大项。下面的代码是伪代码,并不完全正确。 (例如,我认为Add()应该覆盖了一个函数,但我将其编码为一个过程)。但这给出了总体思路。当然,此代码仅跟踪一个项目:最近添加的最大项目。如果需要列出所有计数最大的项目,则可以保留一个字符串列表,而不是fLargestWordSoFar和fLargestCountSoFar。

即使您在添加项目后增加计数,也可以扩展下面的代码,以类似于Add()的方式轻松地处理它们。

type
  MyTDictionary = object(TDictionary) // almost definitely not correct syntax here...
  private
    fLargestCountSoFar: Integer;
    fLargestWordSoFar: String;
  public
    procedure Add( S: String; I:Integer); override;
  end;

implementation

procedure MyTDictionary.Add( S: String; I:Integer);
begin
  if (I > fLargesteCountSoFar) then
  begin
    fLargestCountSoFar := I;
    fLargestWordSoFar  := S;
  end;
  inherited Add( S, I);
 end;

10-08 04:46