Sort datatable for subpart rows

o achieve the sorting of the sub-items while keeping the packages in their original order, you can follow these steps in UiPath:

  1. Read the input DataTable (dt_Input).
  2. Iterate through the rows of the DataTable to identify the package rows and the item rows.
  3. Create a new DataTable (dt_Output) with the same structure as dt_Input.
  4. Use a temporary DataTable to hold the items for each package.
  5. Sort the items within each package by the “Sequence” column.
  6. Add the sorted items back to dt_Output under the corresponding package.
' Read the input DataTable
Dim dt_Input As DataTable = ... ' Your code to read the input DataTable

' Initialize the output DataTable with the same structure as dt_Input
Dim dt_Output As DataTable = dt_Input.Clone()

' Temporary DataTable to hold items for sorting
Dim tempItems As DataTable = dt_Input.Clone()

' Variable to keep track of whether we are within a package
Dim isPackage As Boolean = False

For Each row As DataRow In dt_Input.Rows
    ' Check if the current row is a package
    If row("Reference").ToString.StartsWith("Package") Then
        ' If we were in a package, sort the items and add them to dt_Output
        If isPackage AndAlso tempItems.Rows.Count > 0 Then
            ' Sort the temporary items DataTable
            Dim sortedRows = tempItems.AsEnumerable().OrderBy(Function(r) r.Field(Of Integer)("Sequence")).CopyToDataTable()
            For Each sortedRow As DataRow In sortedRows.Rows
                dt_Output.ImportRow(sortedRow)
            Next
            ' Clear the temporary items DataTable for the next package
            tempItems.Clear()
        End If
        ' Add the package row to dt_Output
        dt_Output.ImportRow(row)
        ' Set the flag to true as we are now in a package
        isPackage = True
    Else
        ' Add the item row to the temporary DataTable
        tempItems.ImportRow(row)
    End If
Next

' After the last package, sort and add any remaining items
If isPackage AndAlso tempItems.Rows.Count > 0 Then
    Dim sortedRows = tempItems.AsEnumerable().OrderBy(Function(r) r.Field(Of Integer)("Sequence")).CopyToDataTable()
    For Each sortedRow As DataRow In sortedRows.Rows
        dt_Output.ImportRow(sortedRow)
    Next
End If

' Now dt_Output contains the sorted items under each package