开发者

LINQ: Paging technique, using take and skip but need total records also - how to implement this?

I have implemented a paging routine using skip and take. It works great, but I need the total number of records in the table prior to calling Take and Skip.

I know I can submit 2 separate queries.

  1. Get Count
  2. Skip and Take

But I would prefer not to issue 2 calls to LINQ.

开发者_StackOverflow社区

How can I return it in the same query (e.g. using a nested select statement)?

Previously, I used a paging technique in a stored procedure. I returned the items by using a temporary table, and I passed the count to an output parameter.


I'm sorry, but you can't. At least, not in a pretty way.

You can do it in an unpretty way, but I don't think you like that:

var query = from e in db.Entities where etc etc etc;

var pagedQuery = 
    from e in query.Skip(pageSize * pageNumber).Take(pageSize)
    select new
    {
        Count = query.Count(),
        Entity = e
    };

You see? Not pretty at all.


There is no reason to do two seperate queries or even a stored procedure. Use a let binding to note a sub-query when you are done you can have an anon type that contains both your selected item as well as your total count. A single query to the database, 1 linq expression and your done. TO Get the values it would be jobQuery.Select(x => x.item) or jobQuery.FirstOrDefault().Count

Let expressions are an amazing thing.

var jobQuery = (
                from job in jc.Jobs
                let jobCount = (
                                    from j in jc.Jobs
                                    where j.CustomerNumber.Equals(CustomerNumber)
                                    select
                                        j
                                ).Count()
                where job.CustomerNumber.Equals(CustomerNumber)
                select
                new
                {
                    item = job.OrderBy(x => x.FieldName).Skip(0).Take(100),
                    Count = jobCount
                }
            );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜