使用LINQ分页搜索结果SQL [英] Paginated search results with LINQ to SQL

查看:105
本文介绍了使用LINQ分页搜索结果SQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是获得与分页结果的最佳模式的的LINQ to SQL 的?

What's the best pattern to get paginated results with LINQ to SQL?

我有以下情形:

假如我想通过的描述的搜索的项目的表。我可以很容易做到:

Suppose I want to search items table by description. I can easily do:

public IQueryable<Item> FindItemsByDescription(string description)
{
   return from item in _dc.Items
          where item.Description.Contains(description);
}

现在,这将是进行分页这个结果集的最佳方式?

Now, what would be the best way to paginate this result set?


  1. 我应该执行的计数的这样做是为了找出结果集的大小,然后限制按照我想要的这个查询前查询?我觉得这是要走的路。

  2. 我应该执行完整的查询,以从数组大小计数,并从该数组只返回一个分页子集?我觉得这将是一个巨大的浪费时间,如果结果是够大...或者是的LINQ to SQL 的在这里做一些魔法?

  1. Should I perform a count query before doing this to find out the result set size and then limit this query according to what I want? I feel like this is the way to go.
  2. Should I perform the full query, take the count from the array size and return only a paginated subset from this array? I feel like this will be a huge waste of time if the resultset is big enough... Or is LINQ to SQL doing some magic here?

有没有的的LINQ to SQL 的执行此操作常见的模式?

Is there a LINQ to SQL common pattern for performing this operation?

编辑:我的必须的澄清一个小东西。我知道以和Skip方法。但是,在使用前的跳过后,我应该怎么得到的结果在总数该查询检索?

I must clarify a one little thing. I am aware of Take and Skip methods. But, before using Take and Skip, how should I get the total count of results that query would retrieve?

推荐答案

分页模式是非常简单的。它涉及到使用跳过(中)和Take()扩展方法如下:

The pattern for paging is very simple. It involves the use of the Skip() and Take() extension methods as follows:

public IQueryable<Item> FindItemsByDescription(string description, int pageIndex, int pageSize)
{
   return from item in _dc.Items
          where item.Description.
          Contains(description).
          Skip((pageIndex - 1) * pageSize).
          Take(pageSize);
}

更新::要获得总数只需使用Count()方法:

UPDATE: To get the total count simply use the Count() method:

int totalCount = from item in _dc.Items
                 where item.Description.
                 Contains(description).Count();

int numberOfPages = (int)(totalCount/pageSize);

根据您将如何显示的记录,您可以使用numberOfPages显示为Y的页面X......第1页10等。

Depending on how you are going to the display the records, you can use the numberOfPages to display a navigation bar with "Page X of Y" ... Page 1 of 10, etc..

这篇关于使用LINQ分页搜索结果SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆