How to order Record in Delphi (similar to ORDER BY)?

Asked

Viewed 1,072 times

1

I bring some bank records with a specific sorting and play into a vector of the type record. Then I need to add more items in this array keeping the initial sort. How the sort is done in the SQL the records that are added later end up going to the end of the vector.

I want to know if there is any way to reorder this vector in the same way as in ORDER BY of SQL having the option to sort by several fields. I use mORMot but I haven’t found anything in the documentation to do that either.

I managed to find an example that does the ordering, it works perfectly, but only does for a field. Follow the code:

Record example:

TRegistro = record
   CODIGO: Integer;
   NOME: string;
   DATA: TDateTime;
   CIDADE: string;
end;
TRegistros = array of TRegistro;

Ordination:

procedure SortArray(var Matriz: TRegistros);
var
   Posicao1, Posicao2: Integer;
   Temporario: TRegistro; // Variável Temporária para Alternar Valores
begin
   for Posicao1 := 0 to Length(Matriz) - 1 do
   begin
      for Posicao2 := 0 to (Length(Matriz) - 2) do
      begin
         if (Matriz[Posicao2].CODIGO > Matriz[Posicao2 + 1].CODIGO ) then // Ordem Crescente
         begin
            Temporario := Matriz[Posicao2];
            Matriz[Posicao2] := Matriz[Posicao2 + 1];
            Matriz[Posicao2 + 1] := Temporario;
         end;
      end;
   end;
end;

2 answers

1

When I go to sort, I prefer to do with WHILE, because we have total control over the iterator. In the case of FOR we cannot change it.

var
  i: Integer;
  Temporario: TRegistro;
begin
  i := 0;
  while (i < High(Matriz)) do
    begin
      if (Matriz[i].CODIGO > Matriz[i + 1].CODIGO) then
        begin
          Temporario := Matriz[i + 1];
          Matriz[i + 1] := Matriz[i];
          Matriz[i] := Temporario;
          i := 0;
        end
      else
        Inc(i, 1);
    end;
end;

I couldn’t test it, but I think it might help you.

  • So, only this one only does the ordering for one field. I needed something similar to ORDER BY of SQL, sort through several fields.

0


I managed to solve using the Sort of TDynArray of mORMot. The Sort takes a function as a parameter and in it I pass the function that compares the records for sorting. I did a comparison function and Arnaud Bouchez did a reworking on it:

function OrderBy(const A, B): Integer;
var
   ra: TRegistro absolute A;
   rb: TRegistro absolute B;
begin
   result := ra.COD_USUARIO - rb.COD_USUARIO;
   if result <> 0 then
      exit;
   result := ra.COD_PRIORIDADE - rb.COD_PRIORIDADE;
   if result <> 0 then
      exit;
   if ra.DATA < rb.DATA then
      result := -1
   else if ra.DATA > rb.DATA then
      result := 1;
end;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.