Sal*_*dor 5 delphi generics dictionary delphi-xe
我有一个像这样声明的TDictionary TDictionary<String,Integer>,现在我想获得存储在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;
Run Code Online (Sandbox Code Playgroud)
您是否曾经删除过项目或减少项目的数量?如果没有,您可以考虑创建 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;
Run Code Online (Sandbox Code Playgroud)