Reputation: 833
I have a large amount of data in the database. I want to filter the result and get a specific number of product
For example: the PageSize=100. i want to get 100 products on each page, and the product's description contains the string "Laptop"
Products = repository.Products
.OrderByDescending(p => p.Date)
.Where(x=>x.Description.Contains("%Laptop%")
.Skip((page - 1) * PageSize)
.Take(PageSize);
This query timed out since the query filters a large result before retrieving the first 100 products
But if I write
Products = repository.Products
.Skip((page - 1) * PageSize)
.Take(PageSize)
.OrderByDescending(p => p.Date)
.Where(x=>x.Description.Contains("%Laptop%");
Then page 1 doesn't have 100 products because the query retries 100 products first and then filtering
What should I do to retrieving 100 products (contain the string"Laptop") and not get time out error?
Upvotes: 0
Views: 119
Reputation: 22794
Where
first, order next, take afterwards.
Like this:
Products = repository.Products
.Where(x=>x.Description.Contains("Laptop");
.OrderByDescending(p => p.Date)
.Skip((page - 1) * PageSize)
.Take(PageSize)
Note, contains get turned into like %input%
, so no need to surround it with %
s ;)
Upvotes: 2