English 中文(简体)
linq paging - get total rows
原标题:

i have a question about linq. I m using Skip and Take to do paging:

(from l in db.ProductList
          select l).Skip((page - 1) * row_per_page).Take(row_per_page)

It work, and i need retrieve total rows of product list to calculate max page. I think i must use another query to count rows but have another way to do this in one query above?

问题回答

To get a count of the rows, use the .Count() extension method

var count = (from l in db.ProductList select l).Count();

The bottom line is you will have to enumerate all items to get the total page number. But you would like to enumerate them only once. I suggest you try GroupBy method to get a IEnumerable> "pages". Then you can use pages.Count() to get page count. Or you can enumerate pages to get each page of items. The GroupBy query will be only executed once.

There isn t a way to get both the total number of rows and a "skip/take" subset of those rows in the same query.

Is there a reason that you need this in two queries?





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签