繁体   English   中英

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

[英]How to add data from an array into a TRichEdit from smallest to largest in Delphi

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

有三个主要步骤可以解决您的问题。

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

pas 文件:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM