TBA
TBA

Reputation: 1187

linq: how to get sorted records from last ID

I have the following table,

ItemTable, 

Col1 : ItemID(int)
Col2 : MRP(Decimal)

To one of the application I needed to pass selected number of items at a time, They will send me the lastId which I passed to them, the initial requirement was to pass the newest items, which I was able to get it using following query,

var itemList = itemRepository.AsQueryable()
             .Where(r => r.ProductID == productID && r.IsActive == true && r.ItemID< lastId)                                            
             .OrderByDescending(r => r.ItemID)
             .Take(numberOfItems)
             .ToList(); 

However now there is a sort option added to it, which is the MRP column, though again i have only the last Id with me, how could I will able to get this? I tried with the following query, no luck.

var itemList = itemRepository.AsQueryable()
                 .Where(r => r.ProductID == productID && r.IsActive == true && r.ItemID< lastId)                                            
                 .OrderByDescending(r => r.ItemID)
                 .OrderBy(r => r.MRP)
                 .Take(numberOfItems)
                 .ToList(); 

UPDATE : Working Code

As per CamperWill's suggesstion I updated my code and works great with skip.

var itemList = itemRepository.AsQueryable()
                     .Where(r => r.ProductID == productID && r.IsActive == true)
                     .OrderBy(r => r.MRP)
                     .Skip(pageNumber * numberOfItems)
                     .Take(numberOfItems)
                     .ToList(); 

Upvotes: 0

Views: 633

Answers (1)

CamperWill
CamperWill

Reputation: 108

LastID will not help you with paging if you are sorting by a different field (MRP). Also, as indicated in the comments above, the first ordering is effectively ignored by adding the second.

You could consider tracking the page number that is requested and use the Skip() extension.

// input parameter 'page'
var itemList = itemRepository.AsQueryable()
    .Where(r => r.ProductID == productID && r.IsActive == true)       
    .OrderBy(r => r.MRP)
    .Skip( (page-1)*numberOfItems )
    .Take(numberOfItems)
    .ToList();

Upvotes: 2

Related Questions