Link to home
Start Free TrialLog in
Avatar of aztec
aztec

asked on

Find index of TList item

Hi...
   I've created a TList that looks like this:

Type
  AList = record
    cc_name : string;
    cc_count : longint;
  end;

  PMyList = ^AList;

Var
  ccList : TList;
  ccRec : PMyList;


I populate this list with records, then later I want to find the index in this list of the item with cc_name equal to for instance, "BOB". How would I do this?

Thanks
   Shawn
Avatar of Lee_Nover
Lee_Nover

simply like :

with ccList do
  for I:=0 to Count-1 do
    if PMyList(Items[I])^.cc_name = SearchString then
    begin
      Result:=I;// or whatever you do ...
      break;
    end;
Avatar of aztec

ASKER

ok, but what about using the "IndexOf" thing? Won't that work somehow?

Shawn
You can only compare pointers to your items(vars) by "IndexOf".
try to use TStringList
Avatar of aztec

ASKER

DragonSlayer - can I still add records of the type I mention above (a string item and a longint item) to a TStringList? And I'll still be able to use the IndexOf method?
You can, for example, do this

var
  MyStringList: TStringList;

in your OnCreate:

MyStringList := TStringList.Create;

and in wherever your data retrieval algorithm is:

var
  ccRec: PMyList;
  i: Integer;
begin
  // let's say you have a bunch of data
  for i := 0 to DataCount - 1 do
  begin
    New(ccRec);
    ccRec^.cc_name = ReadData; // assuming this is your data retrieval function
    ccRec^.cc_count = ReadCount; // see comment as above
    MyStringList.AddObject(ccRec^.cc_name, TObject(ccRec));
  end;
end;

and in your OnDestroy

for i := MyStringList.Count - 1 downto 0 do
  Dispose(PMyList(MyStringList.Objects[i]));
MyStringList.Free;


and now to retrieve:

function Retrieve(const cName: string): AList;
var
  i: Integer;
begin
  i := MyStringList.IndexOf(cName);
  if i < 0 then
    ShowMessage('Error') // or whatever error msg/default values you want to return
  else
    Result := PMyList(MyStringList.Objects[i])^;
end;



HTH
DragonSlayer.
but with a stringlist you have double lists
I like to keep code optimized as possible
as for speed as for memory
depends what you're doing anyway
Avatar of Tomas Helgi Johannsson
Hi!

You could override the TList and impliment a Find function
similar to TListSortCompare(...). Look at the code for the
TList class how it is done.

Regards,
Tomas Helgi
ASKER CERTIFIED SOLUTION
Avatar of TOndrej
TOndrej

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial