Is there a safe way to mutate the value of a tdictionary, while iterating?
The first naive try:
var p: tpair<keytype,valuetype>;
begin
for p in coll do
// p.value is readonly for valuetypes and their fields.
end;
failed, and also wrapping the valuetype in a RECORD doesn't help.
Iterating over keys and using dosetvalue might work, but it is private only.
I could of course use a reference type, but that seems a bit silly to me, since the state is an integer. Not elegant.
Added, complete sample:
program gendicttest;
// tests if you can set valuetype key.
{$APPTYPE CONSOLE}
uses
generics.collections;
type
TCycleList = tdictionary<integer,integer>; // the value a record type doesn't work either.
var cyclelist :TCycleList;
p : tpair<integer,integer>;
j:integer;
begin
cyclelist:=tcyclelist.Create;
cyclelist.Add(3,4);
for p in cyclelist do
writeln(p.Key, ' ',p.Value);
if cyclelist.TryGetValue(3,j) then
cyclelist.AddOrSetValue(3,j+1);
for p in cyclelist do
p.Value:=0; // <-- here, and alternative to do this.r
for p in cyclelist do
writeln(p.Key, ' ',p.Value);
end.
cyclelist.AddOrSetValue(p.Key, 0);
– nilContains
. Or maybe justclyclelist[p.Key] := 0;
because TDictionary has a convenient default indexed property for reading and writing values:property Items[const Key: TKey]: TValue read GetItem write SetItem; default;
– nil