Everything about generic TList
. I have this structure:
Type
TExtract = record
Wheel: string;
Extract: array [1..5] of Byte;
end;
There is only a single way I've found to search through a list with a specific value.
I'll reuse Cosmin Prund example :
uses Generics.Defaults; // this provides TDelegatedComparer
uses Math; // this provides Sign()
function SearchList(Date:TDate; Sort:Boolean; List:TList): Integer;
var Dummy : TEstr;
begin
// If the list is not sorted, sort it. We don't know if it's sorted or not,
// so we rely on the "Sort" parameter
if Sort then List.Sort(TDelegatedComparer.Construct(
function (const L, R: TEstr): Integer
begin
Result := Sign(L.Date - R.Date);
end
);
// Call BinarySearch() to look up the record based on Date alone
if not List.BinarySearch(Dummy, Result, TDelegatedComparer.Construct(
function (const L, R: TEstr): Integer
begin
//By implementation, the binarySearch Dummy parameter is passed in the "R" parameter of the Comparer function. (In delphi 2010 at least)
Result := Sign(L.Date - Date); //Use the Date parameter instead of R.Date
end) then
Result := -1;
end;
This approach, however, is only valid "by implementation" and not "by design" (as far as I know). In other word, it is prone to break between versions of Delphi. So this is only advisable to use this approach for items that can be "performance expensive" to create. If you do so, I strongly advise to add something like this in your code.
{$IF RTLVersion > *YourCurrentVersion*}
{$MESSAGE WARNING 'Verify if BinarySearch implementation changed'}
{$IFEND}
p That way, next time you build this code in a newer version of Delphi, you will automatically get a warning telling you to make sure your code will still work as expected. But this could still causes problems if your code needs to support more than 1 version of Delphi at the same time.