TObjectListde Değere Göre Sıralama

Yazdığınız makaleleri ve üyelerimizin işine yarayacağını düşündüğünüz kodlarınızı gönderebilirsiniz. Bu foruma soru sormayın!
Cevapla
ismailkocacan
Üye
Mesajlar: 88
Kayıt: 25 Eyl 2011 06:11
Konum: İstanbul
İletişim:

TObjectListde Değere Göre Sıralama

Mesaj gönderen ismailkocacan »

Diyelim ki elinizde Key ve Value lardan oluşan bir Object List var.
Key'iniz String.
Value niz Sayı.
Sizde Valuye göre sıralamak istiyorsunuz. :D

Çözüm :

Kod: Tümünü seç

unit Unit1;

interface

uses
  Windows,
  Messages,
  SysUtils,
  Variants,
  Classes,
  Graphics,
  Controls,
  Forms,
  Dialogs,
  StdCtrls,
  Generics.Defaults,
  Generics.Collections;
type


  //Liste saklayacağımız ikili değer
  TItemKeyValuePair = class
    fvalue: Integer;
    fkey: string;
  end;

  //Object Listemiz
  TObjectList = class(TObjectList<TItemKeyValuePair>)
  end;

  TForm1 = class(TForm)
    btnSortList: TButton;
    ListBox1: TListBox;
    procedure btnSortListClick(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.btnSortListClick(Sender: TObject);
var
  objList: TObjectList<TItemKeyValuePair>;
  itemKeyVal: TItemKeyValuePair;
begin
  objList := TObjectList.Create();

  itemKeyVal := TItemKeyValuePair.Create;
  itemKeyVal.fvalue := 20;
  itemKeyVal.fkey := 'dosya1';
  objList.Add(itemKeyVal);

  itemKeyVal := TItemKeyValuePair.Create;
  itemKeyVal.fvalue := 10;
  itemKeyVal.fkey := 'dosya3';
  objList.Add(itemKeyVal);

  itemKeyVal := TItemKeyValuePair.Create;
  itemKeyVal.fvalue := 4;
  itemKeyVal.fkey := 'dosya2';
  objList.Add(itemKeyVal);

  //value ye göre sırala
  objList.Sort(
    TComparer<TItemKeyValuePair>.Construct(
      function(const left,rigth:TItemKeyValuePair): Integer
      begin
          if left.fvalue < rigth.fvalue then
              Result := -1
            else if left.fvalue > rigth.fvalue then
              Result := 1
            else
              Result := 0;
      end));


  for itemKeyVal in objList do
  begin
    ListBox1.Items.Add(
    itemKeyVal.fkey+' ='+
    IntToStr(itemKeyVal.fvalue));
  end;

  objList.Free;

end;

end.
sortTObjectList.rar
XE Kaynak Kod
(84.39 KiB) 107 kere indirildi
Umarım ifade edebilmişimdir :mrgreen:
Saygılarımla
İsmail Kocacan
Cevapla