LINQ: Paging technique, using take and skip but ne

2019-04-10 05:04发布

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.

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.

2条回答
家丑人穷心不美
2楼-- · 2019-04-10 05:42

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
                }
            );
查看更多
虎瘦雄心在
3楼-- · 2019-04-10 05:50

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.

查看更多
登录 后发表回答