Brian Var
Brian Var

Reputation: 6227

How to query last 'n' number of records from a table?

I'm using an Azure mobile service with a C# back end for my app, but I'm not sure how to query the last 16 records that were added to the DB.

I've come across the statement, and I thought that could query the "last" 16 records but it doesn't:

var result = await itemModelTable
                .Take(16)
                .ToListAsync();

Does anyone have an idea how to form this query?

Upvotes: 1

Views: 120

Answers (1)

Habib
Habib

Reputation: 223257

There is no concept of Last, You need to order your collection and then use Take like:

var result = await itemModelTable
                .OrderByDescending(r=> r.SomeField)
                .Take(16)
                .ToListAsync();

For "Last", you need to use OrderByDescending and then use Take.

If no order is specified, then the records returned could be in any order. Same like SQL Select statement without order by clause.

Upvotes: 3

Related Questions