如何在Delphi中将数据从数组添加到TRichEdit中从最小到最大

问题描述 投票:-2回答:1

我想读取名称和相应的值,我将它们存储在一个数组中。我想知道如何读取数组,将最高数字添加到TRichEdit,然后继续读取数组并添加第二高,第三高等等,直到没有更多的值。

delphi
1个回答
1
投票

解决问题有三个主要步骤。

  1. 你必须是未排序的数组(创建一个)
  2. 对数组进行排序
  3. 将已排序的项添加到TRichEdit

不是文件:

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    RichEdit1: TRichEdit;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

uses
    Generics.Defaults
  , Generics.Collections
  ;

{$R *.dfm}

type
  TMyRec = packed record
    int : integer;
    str : string;
    constructor create( int_ : integer; str_ : string );
  end;

constructor TMyRec.create( int_ : integer; str_ : string );
begin
  int := int_;
  str := str_;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  myRecs : array of TMyRec;
  myRecComparer : IComparer<TMyRec>;
  myRec : TMyRec;
begin
  setLength( myRecs, 5 );
  try
    // Create and fill up the unsorted array
    myRecs[0] := TMyRec.create( 3, '3' );
    myRecs[1] := TMyRec.create( 5, '5' );
    myRecs[2] := TMyRec.create( 1, '1' );
    myRecs[3] := TMyRec.create( 4, '4' );
    myRecs[4] := TMyRec.create( 2, '2' );

    // Sort the array
    myRecComparer := TComparer<TMyRec>.Construct( function ( const left_, right_ : TMyRec ) : integer begin result := left_.int - right_.int end );
    TArray.sort<TMyRec>( myRecs, myRecComparer );

    // Add the sorted array items to the TRichEdit control
    RichEdit1.lines.clear;
    for myRec in myRecs do
      RichEdit1.Lines.Add( myRec.str );

  finally
    setLength( myRecs, 0 );
  end;
end;

end.

dfm文件:

object Form1: TForm1
  Left = 400
  Top = 219
  Caption = 'Form1'
  ClientHeight = 138
  ClientWidth = 200
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  PixelsPerInch = 96
  TextHeight = 13
  object Button1: TButton
    Left = 8
    Top = 103
    Width = 185
    Height = 25
    Caption = 'Add orders records'
    TabOrder = 0
    OnClick = Button1Click
  end
  object RichEdit1: TRichEdit
    Left = 8
    Top = 8
    Width = 185
    Height = 89
    Font.Charset = EASTEUROPE_CHARSET
    Font.Color = clWindowText
    Font.Height = -11
    Font.Name = 'Tahoma'
    Font.Style = []
    ParentFont = False
    TabOrder = 1
  end
end
© www.soinside.com 2019 - 2024. All rights reserved.