Jump to content
markus_ja

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;

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×