1

i have a table with 100+ rows ,i want to row number 10 to 20 using entity frame work ,but i can't understand how to write the code

my code is

 db.Products.Where(p => p.Name == "product").Take(10, 20).ToList());

but it showing error

Sk Asraf
  • 163
  • 2
  • 14

3 Answers3

8

Use .Skip() and Take()

db.Products.Where(p => p.Name == "product").Skip(10).Take(10).ToList();

^Also the error is Extra ) at the end.

Note *(Suggested by Tim Schmelter & MatBailie) : Order your resultset before paging the rows to avoid arbitrary and unpredictable output.

Community
  • 1
  • 1
Shaunak D
  • 20,588
  • 10
  • 46
  • 79
  • 1
    Just as I'd posted the same in the comments! Spot on. – Geoff James Jun 21 '16 at 09:51
  • @GeoffJames, right. But the actual issue - the error as explained by OP is extra `)` at the end. :) – Shaunak D Jun 21 '16 at 09:53
  • Thanks @Shaunak, just spotted that - Copy/pasting quickly is a dangerous thing at times! – Geoff James Jun 21 '16 at 09:55
  • 2
    As per a comment on the OP, surely you need to order the set before skipping 10 and taking the next 10? *(If this generates SQL without an ORDER BY, the 10 rows you get are arbitrary, and while they're unlikely to vary, they might.)* – MatBailie Jun 21 '16 at 09:55
  • @MatBailie, true! I'll add that as a suggestion. – Shaunak D Jun 21 '16 at 09:57
  • 1
    yes it showing error like.**The method 'Skip' is only supported for sorted input in LINQ to Entities. The method 'OrderBy' must be called before the method 'Skip'** – Sk Asraf Jun 21 '16 at 10:02
  • the exact query should be `db.Products.Where(p => p.Name == "product").OrderBy(x=>x.Name).Skip(10).Take(10).ToList();` orderBy is needed. – Sk Asraf Jun 21 '16 at 10:16
  • 2
    @SkAsraf: but you notice that this query is pointless? You are filtering by a `ProductName`, then you are ordering by name. So you either get only one record, then ordering and paging would be pointless or you get many records with this `ProductName`, then the `OrderBy` would be redundant because all rows had the same name and you'd again get arbitrary rows. Note that you can also append `...ThenBy(p => p.OtherColumn)` after `OrderBy` to order by multiple columns. – Tim Schmelter Jun 21 '16 at 10:20
0

You can use the Skip method:

db.Products.Where(p => p.Name == "product").Skip(10).Take(10).ToList();
Simon
  • 1,081
  • 9
  • 14
0

The answer is simple:

db.Products.Where(p => p.Name == "product").Skip(10).Take(10).ToList();
Yurii N.
  • 5,455
  • 12
  • 42
  • 66
  • orderBy is need the code will be `db.Products.Where(p => p.Name == "product").OrderBy(x=>x.Name).Skip(10).Take(10).ToList();` – Sk Asraf Jun 21 '16 at 10:18