2

I need to sort DataTables, however the sort-by-columns vary.

Scenario #1, DataTable1 should be sorted by "Column1".

Scenario #2, DataTable2 should be sorted by "Column1, Column2".

Below is my first attempt at creating a helper function for this purpose. This works ok.

Private Sub SortDataTable(ByRef dataTable As DataTable, ByVal sortColumnNames As List(Of String))
    'Validation (not shown here)

    Dim sortOrder = String.Join(", ", sortColumnNames)

    dataTable.DefaultView.Sort = sortOrder
    dataTable = dataTable.DefaultView.Table
End Sub

I tried implementing this in LINQ, however, I don't know how to pass multiple sort-by-columns to the lambda function. Work-in-progress code shown below.

Private Sub SortDataTable(ByRef dataTable As DataTable, ByVal sortColumnNames As List(Of String))
        'Validation (not shown here)

        dataTable.AsEnumerable().OrderBy(Function (row) row(sortColumnNames(0))).ThenBy(...)
    End Sub

How should I pass multiple sort-by-columns to the OrderBy/ThenBy extension methods?

0

1 Answer 1

3

Something like that:

Private Function SortDataTable(table As DataTable, ParamArray columns As String()) As DataTable
    If columns.Length = 0 Then
        Return table
    End If

    firstColumn = columns.First()

    Dim result = table.AsEnumerable().OrderBy(Function(r) r(firstColumn))

    For Each columnName As var In columns.Skip(1)
        result = result.ThenBy(Function(r) r(columnName))
    Next

    Return result.AsDataView().ToTable()

End Function

Converted from this C# code ( I've written this in C# and then used http://www.developerfusion.com/tools/convert/csharp-to-vb/ ):

DataTable SortDataTable(DataTable table, params string[] columns)
{
    if (columns.Length == 0)
    {
        return table;
    }

    firstColumn = columns.First();

    var result = table.AsEnumerable().OrderBy(r => r[firstColumn]);

    foreach (var columnName in columns.Skip(1))
    {
        result = result.ThenBy(r => r[columnName]);
    }

    return result.AsDataView().ToTable();
}

PS: didn't test that. But that's very simple, so should be no problems.

Sign up to request clarification or add additional context in comments.

1 Comment

Damn! I missed storing the LINQ expression into a variable, that's why ThenBy wasn't available. Thanks much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.