转:c# Linq 的分页

转:http://www.cnblogs.com/leleroyn/archive/2008/05/14/1196811.html

很多学习Linq的朋友肯定有自己所不同的方法,考虑这个问题我所想到的是

用Take(),Skip(),TakeWhile(),SkipUntil()中的方法来实现

首先看Take()是否可用

Take方法的作用是从结果中取固定数量的值,

MydbDataContext mydb=new MydbDataContext("server=.;database=mydb");

var query=from p in mydb.Products                orderby p.id descending                 select p;//取出Products中所用的项按降序排列 如果直接用take()

var q=query.take(n) 这样只能取出前条n记录,但是还是让我们看到了分页的曙光,还是还有个skip吗,skip可以取出除去满足条件的剩下的记录。如果我们要把数据以每页pagesize的数量来进行分页,很简单,很skip(pagersize*pagenum)然后在剩下的记录中take(pagesize)不就得到了想要的数据了么。

 

varq=query.skip(pagesize*pagenum).take(pagesize) 就这么简单。

希望朋友们提供更好的方法来进行分页,同时对这个方法的优劣性,进行批评指导 附上运行时生成的SQL(感谢紫色阴影Boler Guo ) sql server2000: SELECT TOP 20 [t0].[CustomerID], [t0].[CompanyName], [t0].[ContactName], [t0].[ContactTitle], [t0].[Address], [t0].[City], [t0].[Region], [t0].[PostalCode], [t0].[Country], [t0].[Phone], [t0].[Fax] FROM [dbo].[Customers] AS [t0] WHERE NOT (EXISTS( SELECT NULL AS [EMPTY] FROM ( SELECT TOP 10 [t1].[CustomerID] FROM [dbo].[Customers] AS [t1] ) AS [t2] WHERE [t0].[CustomerID] = [t2].[CustomerID] )) sql server 2005 SELECT TOP 10 [t1].[CustomerID], [t1].[CompanyName], [t1].[ContactName], [t1].[ContactTitle], [t1].[Address], [t1].[City], [t1].[Region], [t1].[PostalCode], [t1].[Country], [t1].[Phone], [t1].[Fax] FROM ( SELECT ROW_NUMBER() OVER (ORDER BY [t0].[ContactName]) AS [ROW_NUMBER], [t0].[CustomerID], [t0].[CompanyName], [t0].[ContactName], [t0].[ContactTitle], [t0].[Address], [t0].[City], [t0].[Region], [t0].[PostalCode], [t0].[Country], [t0].[Phone], [t0].[Fax] FROM [dbo].[Customers] AS [t0] ) AS [t1] WHERE [t1].[ROW_NUMBER] > @p0 ORDER BY [t1].[ContactName] -- @p0: Input Int32 (Size = 0; Prec = 0; Scale = 0) [50] -- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 3.5.20XXX.X

你可能感兴趣的:(LINQ)