28 Ağustos 2012 Salı

TObjectListde Değere Göre Sıralama

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.

Çözüm :

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)
  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;
  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.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.