3

I'm very new to LINQ and I am not sure how to use it properly yet.

I have connection to MYSQL and I have over 3k rows in a table and at the moment I use LIMIT in SQL syntax to go through the data page by page and I would like to avoid that due to many SQL queries being sent through the connection. This is my currect Work-In-Progress LINQ code:

var test = from Item in ItemList
           orderby Item.Id ascending
           select Item;

Now, with my SQL syntax I had LIMIT 0 , 200 to get first 200 rows, and on page 2 that code would be LIMIT 200 , 200. I know I can limit linq with .Take(x) but I want to "take" 200 records where x is starting index. Sorry about the bad explanation, as I said, I'm new to LINQ.

Thank you! :)

DethoRhyne
  • 930
  • 1
  • 9
  • 29

1 Answers1

6

You can use the Skip method to skip the first n rows, then Take the next n rows.

For example:

var test = (from Item in ItemList
           orderby Item.Id ascending
           select Item).Skip(200).Take(200);

https://msdn.microsoft.com/library/bb358985(v=vs.100).aspx

Steve
  • 9,335
  • 10
  • 49
  • 81
  • That did the trick! Thank you very much! :) – DethoRhyne Feb 24 '16 at 12:28
  • @DethoRhyne keep in mind I'm not sure of the performance of this off the top of my head, you'll need to look into the generated SQL to make sure it's working as expected at the lower level. – Steve Feb 24 '16 at 12:29
  • 1
    Don't worry, SQL side is ok and the SQL Connection works as expected loading the database rows as objects (ID, username, etc..) As I'm working on a database viewer/console type of thing I need to see and review results and pagination was important due to high count of results. This is why I looked into linq to give my CPU some ease. – DethoRhyne Feb 24 '16 at 12:31