Einzelnen Beitrag anzeigen

Benutzerbild von Sir Rufo
Sir Rufo

Registriert seit: 5. Jan 2005
Ort: Stadthagen
9.454 Beiträge
 
Delphi 10 Seattle Enterprise
 
#16

AW: Sortierte TObjectList - Einträge richtig einfügen

  Alt 17. Jul 2015, 16:09
Du meinst sowas hier?
Delphi-Quellcode:
uses
  Generics.Collections,
  Generics.Defaults;

type
  TZiel = class(TObject)
    WERT1 : Word;
    WERT2 : Word;
    WERT3 : String;
    WERT4 : String;
    WERT5 : Cardinal;
    WERT6 : Int64;
    WERT7 : Int64;
  end;

  TZielListe = class( TObjectList<TZiel> )
  private
    function Compare( const L,R: TZiel) : Integer;
  public
    constructor Create( OwnsObjects: Boolean = true );
    function IndexOfWert3(const Value: string) : Integer;
  end;

function TZielListe.IndexOfWert3(const Value: string) : Integer;
var
  LItem : TZiel;
begin
  LItem := TZiel.Create;
  try
    LItem.Wert3 := Value;
    if not BinarySearch(
      LItem,
      Result,
      TComparer<TZiel>.Construct(
        function (const L, R: TZiel): Integer
        begin
          Result := AnsiCompareText( L.Wert3, R.Wert3 );
        end ) ) then
      Result := -1;
  finally
    LItem.Free;
  end;
end;

function TZielListe.Compare( const L,R: TZiel) : Integer;
begin
  Result := TComparer<string>.Default.Compare( L.Wert3, R.Wert3 );
end;

constructor TZielListe.Create( OwnsObjects: Boolean );
begin
  inherited Create( TComparer<TZiel>.Construct( Compare ), OwnsObjects );
end;
Andererseits kannst du auch den Standard-Comparer nutzen, wenn der schon passt:
Delphi-Quellcode:
function TZielListe.IndexOfWert3(const Value: string) : Integer;
var
  LItem : TZiel;
begin
  LItem := TZiel.Create;
  try
    LItem.Wert3 := Value;
    Result := IndexOf( LItem );
  finally
    LItem.Free;
  end;
end;

function TZielListe.Compare( const L,R: TZiel) : Integer;
begin
  Result := AnsiCompareText( L.Wert3, R.Wert3 );
end;

constructor TZielListe.Create( OwnsObjects: Boolean );
begin
  inherited Create( TComparer<TZiel>.Construct( Compare ), OwnsObjects );
end;
Kaum macht man's richtig - schon funktioniert's
Zertifikat: Sir Rufo (Fingerprint: ‎ea 0a 4c 14 0d b6 3a a4 c1 c5 b9 dc 90 9d f0 e9 de 13 da 60)

Geändert von Sir Rufo (17. Jul 2015 um 16:13 Uhr)
  Mit Zitat antworten Zitat