Alaa Alweish
Alaa Alweish

Reputation: 9084

how to Order a DataTable By more than one condition using AsEnumerable().OrderBy?

Just like in TSQL:

select * from aTable where (aCondition) order by AnIntegerField desc, ADateField 

how to sort a DataTable using:

dt.AsEnumerable().OrderBy(--two conditions --)

Upvotes: 0

Views: 3106

Answers (1)

competent_tech
competent_tech

Reputation: 44941

You would use OrderBy first, then ThenBy (for ascending) or ThenByDescending (for descending).

From the Microsoft documentation:

    string[] fruits = { "grape", "passionfruit", "banana", "mango", 
                          "orange", "raspberry", "apple", "blueberry" };

    // Sort the strings first by their length and then 
    //alphabetically by passing the identity selector function.
    IEnumerable<string> query =
        fruits.OrderBy(fruit => fruit.Length).ThenBy(fruit => fruit);

or for VB (since question is tagged with both):

    ' Create an array of strings.
    Dim fruits() As String = _
        {"grape", "passionfruit", "banana", "mango", _
         "orange", "raspberry", "apple", "blueberry"}

    ' Sort the strings first by their length and then 
    ' alphabetically by passing the identity function.
    Dim query As IEnumerable(Of String) = _
        fruits _
        .OrderBy(Function(fruit) fruit.Length) _
        .ThenBy(Function(fruit) fruit)

Upvotes: 4

Related Questions