簡體   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