Mych
Mych

Reputation: 2563

Linq: How do I add an Order By clause to this statement

I have a linq statement that takes an existing datatable and gets a list of distinct years by using a GroupBy and then gets a count of items that have that year and places result in another datatable.

Dim yearQuery = existingDT.AsEnumerable().GroupBy(Function(yi) yi.Field(Of String)(existingDT.Columns("Year")))

Dim yearResults As New DataTable()

yearResults.Columns.Add("Year")
yearResults.Columns.Add("Quantity")

For Each yi In yearQuery 
    yearResults.Rows.Add( yi.Key, yi.Count)
Next

This works great but try as I might I have not been able to figure out how produce the results so that yearResults datatable has the data in descending year order.

Upvotes: 0

Views: 32

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460228

Why is Year a string and not an integer? If you can't change that you always have to parse that value:

Dim orderedYearQuery = existingDT.AsEnumerable().
    GroupBy(Function(row) Int32.Parse(row.Field(Of String)("Year"))).
    OrderByDescending(Function(grp) grp.Key)

Upvotes: 1

Related Questions