Delphi – How to update TLIST when it is an iteration using the for-in loop?

I am trying to learn generics in Delphi, but TList has a very basic problem.

I have successfully created a list of integers and used 1000 Fill it with an odd number. I want to change every number in the list that is divisible by 3. I think I can do something like this.

For I in Mylist Do
Begin
If (I mod 3) = 0 Then
I:=0;
End;

This obviously does not work, so I hope someone will explain that there will be What.

You are using a for..in loop, which uses a read-only enumerator. This Snippet of code:

For I in Mylist Do
Begin
If (I mod 3) = 0 Then
I := 0;
End;

Actually do this:

Enum := Mylist.GetEnumerator;
while Enum.MoveNext do
Begin
I := Enum.Current;
If (I mod 3) = 0 Then
I := 0;
End;

This is why you can’t modify the contents of the list in the for..in loop. You have to use the old-style for loop, using the TList.Items[] property to access the value:

For I := 0 to Mylist.Count-1 Do
Begin
If (Mylist[I] mod 3) = 0 Then
Mylist[I] := 0;
End;

Update: Then delete the zeros, you can do this:

For I := Mylist.Count-1 downto 0 Do
Begin
If Mylist[I] = 0 Then
Mylist.Delete(I);
End;

Or, do this in the initial loop, so you don’t need a second loop:

For I := Mylist.Count-1 downto 0 Do
Begin
If (Mylist[I] mod 3) = 0 Then
Mylist.Delete(I) ;
End;

I tried to learn generics in Delphi, but TList has a very basic problem.

I have successfully created a list of integers and filled it with 1000 odd numbers. I want to change every number in the list that is divisible by 3. I think I can do something like this.

For I in Mylist Do
Begin
If (I mod 3) = 0 Then
I:=0;
End;

This is obviously Doesn’t work, so I hope someone will explain what will be.

You are using a for..in loop, which uses a read-only enumerator. This paragraph Code:

For I in Mylist Do
Begin
If (I mod 3) = 0 Then
I := 0 ;
End;

Actually do this:

Enum := Mylist.GetEnumerator;
while Enum.MoveNext do< br />Begin
I := Enum.Current;
If (I mod 3) = 0 Then
I := 0;
End;

This is why you cannot modify the contents of the list in the for..in loop. You have to use the old-style for loop, using the TList< T> .Items [] property to access the value:

< pre>For I := 0 to Mylist.Count-1 Do
Begin
If (Mylist[I] mod 3) = 0 Then
Myl ist[I] := 0;
End;

Update: Then delete the zeros, you can do this:

For I := Mylist.Count-1 downto 0 Do
Begin
If Mylist[I] = 0 Then
Mylist.Delete(I);
End;

Or , Do this in the initial loop, so you don’t need the second loop:

For I := Mylist.Count-1 downto 0 Do
Begin< br /> If (Mylist[I] mod 3) = 0 Then
Mylist.Delete(I);
End;

Leave a Comment

Your email address will not be published.