Search code examples
delphidelphi-10.1-berlinspring4d

How to create and use a case insensitive IList<string> in Spring4d


I'm trying the following code to create a case insensitive IList:

procedure TForm1.ListButtonClick(Sender: TObject);
var
  MyList: IList<string>;
begin
  MyList := TCollections.CreateList<string>(TStringComparer.OrdinalIgnoreCase());
  MyList.AddRange(['AAA', 'BBB', 'CCC']);
  Memo1.Lines.Add(MyList.IndexOf('aaa').ToString);
end;

However the IndexOf call always returns -1. Should this work? Any suggestions appreciated.

Update: It looks like the comparer is used for sorting, but not for IndexOf. A separate "EqualityComparer" is used for IndexOf, so the question becomes how to change it?

Update2: I just wanted to add to Johan's answer that the list can then be created like so:

MyCIList := TCaseInsensitiveList<string>.Create(
  TStringComparer.OrdinalIgnoreCase(),
  TStringComparer.OrdinalIgnoreCase());

Solution

  • This issue has been resolved in Spring4D hotfix 1.2.1. With the change the code below works as expected.

    procedure TForm1.ListButtonClick(Sender: TObject);
    var
      MyList: IList<string>;
    begin
      MyList := TCollections.CreateList<string>(TStringComparer.OrdinalIgnoreCase());
      MyList.AddRange(['AAA', 'BBB', 'CCC']);
      Memo1.Lines.Add(MyList.IndexOf('aaa').ToString);  // Correctly returns 0.
    end;