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

1

I bring some bank records with a specific order and play into a vector of type record ". Then I need to add more items to that vector by keeping the initial sort. Since the ordering is done in SQL the records that are added then 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 it does in ORDER BY of SQL having the option to sort by multiple fields. I use mORMot too but I have not found anything in the documentation that does this.

I was able to find an example that does the ordering, it works perfectly, but it only does for a field. Here is the code:

Record example:

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

Sorting:

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;
    
asked by anonymous 30.05.2017 / 15:47

2 answers

0

I was able to resolve using Sort of TDynArray of mORMot . The Sort receives a function as a parameter and in it step the function that compares the records to sort. I did a comparison function and Arnaud Bouchez gave a reformulation in her:

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;
    
01.06.2017 / 22:35
1

When I do ordering, I have preference in doing with WHILE, this is why we have full control over the iterator. In the case of FOR we can not 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 could not test, but I think this might help.

    
30.05.2017 / 15:59