Jump to content

Please add Sort to TW3DataSet


Recommended Posts

Hello,

 

please implement a Sort function in the TW3DataSet. Maybe you can use my code?

Unfortunately, I cannot derive my own TDataSet class or create a helper class, because I need access to private fields. Therefore, it would be great to have at implemented in the RTL.

 

Usage:

FDataSet.Sort(['FIELD1', '-FIELD2']);

Use the - sign to sort it descanding.

type
  TW3DataSetSortFieldInfo = class
  public
    property IsDescOrder: boolean;
    property FieldName: string;
    property FieldType: TW3DatasetFieldType;
  end;

procedure TW3Dataset.Sort(aFields: array of String);
var
  leftVal, rightVal: Variant;
  fieldInfo: TW3DataSetSortFieldInfo;
  fieldInfos: array of TW3DataSetSortFieldInfo;

  function CompareVar(aIsDesc: boolean): Integer;
  begin
    if leftVal < rightVal then
      Result := -1
    else
    if leftVal > rightVal then
      Result := 1
    else
      Result := 0;

    if aIsDesc then
      Result := Result * -1;
  end;

begin

  for var i:=0 to aFields.Count - 1 do
  begin
    fieldInfo := TW3DataSetSortFieldInfo.Create;

    fieldInfo.FieldName := aFields[i].ToLower;

    fieldInfo.IsDescOrder := LeftStr(fieldInfo.FieldName, 1) = '-';
    if fieldInfo.IsDescOrder then
      fieldInfo.FieldName := RightStr(fieldInfo.FieldName, fieldInfo.FieldName.Length - 1);

    fieldInfo.FieldType := FFields.FieldByName(fieldInfo.FieldName).Kind;

    fieldInfos.Add(fieldInfo);
  end;

  FCache.Sort(
    function(left, right: TW3DatasetPacket): Integer
    begin
      Result := 0;

      for var i:=0 to fieldInfos.Count - 1 do
      begin
        fieldInfo := fieldInfos[i];

        leftVal := left[fieldInfo.FieldName];
        rightVal := right[fieldInfo.FieldName];

        if fieldInfo.FieldType = ftString then
        begin
          leftVal := TVariant.AsString(leftVal).ToLower;
          rightVal := TVariant.AsString(rightVal).ToLower;
        end;

        Result := CompareVar(fieldInfo.IsDescOrder);

        if (Result <> 0) then
          break;

      end;

    end);
end;
Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...