gpt4 book ai didi

delphi - TClientDataSet 遍历并删除记录,因为某些记录在 while 循环中遍历两次(如果有索引)

转载 作者:行者123 更新时间:2023-12-03 15:50:05 25 4
gpt4 key购买 nike

我有以下代码,它遍历TClientDataSet中的所有数据,我的目的是删除除DocKey=20381之外的所有记录。

但是使用以下代码,您会注意到 DocKey=20381 的记录被遍历了两次(遍历次数 = 6,假设为 5 次,因为我们在 TClientDataSet 中只有 5 条记录)。

如果我们启用这一行 -> D.IndexFieldNames := 'DocKey',那么数据将正确遍历。我可以知道这是 Delphi 的错误吗?或者除了使用 IndexFieldNames 之外还有什么方法可以解决这个问题?

var
D: TClientDataSet;
begin
D := TClientDataSet.Create(Self);
with D do begin
FieldDefs.Add('DocKey', ftInteger);
CreateDataSet;
AppendRecord([20157]);
AppendRecord([20162]);
AppendRecord([20381]);
AppendRecord([20372]);
AppendRecord([20377]);
end;
// D.IndexFieldNames := 'DocKey';

D.First;
while not D.Eof do begin
if D.Fields[0].AsInteger = 20381 then
D.Next
else
D.Delete;
end;
end;

最佳答案

此行为是按照设计的,documented

If the record deleted was the last record in the dataset, then the previous record becomes the current record.

20157 -> delete20162 -> delete20381 -> next20372 -> delete20377 -> delete (last record -> goto previous record -> not eof)

With this line

D.IndexFieldNames := 'DocKey';

不被删除记录成为数据集中的最后一条记录,因此最后一条记录没有删除,而不是该行为。

20157 -> delete20162 -> delete20372 -> delete20377 -> delete20381 -> next

UPDATE

If you want to avoid this - for any reasons I did not know or I could imagine - just check, if the current RecNo is decreased.

var 
D: TClientDataSet;
LRecNo : Integer;
begin
D := TClientDataSet.Create(Self);
with D do begin
FieldDefs.Add('DocKey', ftInteger);
CreateDataSet;
AppendRecord([20157]);
AppendRecord([20162]);
AppendRecord([20381]);
AppendRecord([20372]);
AppendRecord([20377]);
end;
// D.IndexFieldNames := 'DocKey';

D.First;
while not D.Eof do
begin

LRecNo := D.RecNo;

if D.Fields[0].AsInteger = 20381 then
D.Next
else
D.Delete;

if LRecNo > D.RecNo then
Break;

end;
end;

关于delphi - TClientDataSet 遍历并删除记录,因为某些记录在 while 循环中遍历两次(如果有索引),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23558043/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com