c# - 找出项目在哪个页面上

标签 c# linq entity-framework

我在我的应用程序中使用带有 Entity Framework 的 LINQ。我有存储库方法来获取这样的数据页面:

public IEnumerable<Sample> GetPageData(int orderId, int page, int itemsPerPage)
{
    var samples = _context.Set<Sample>()
                          .Where(s => s.OrderId == orderId)
                          .OrderBy(s => s.Id)
                          .Skip(itemsPerPage * page)
                          .Take(itemsPerPage);

    return samples;
}

我想要另一个存储库方法,以便我可以检索样本所在的页面。方法签名类似于:

public int GetPage(int orderId, int sampleId, int itemsPerPage)
{
    // ???
}

我正在努力寻找在 LINQ 中执行此操作的方法。我现在唯一的想法是一页一页地获取页面,直到找到所需的样本。我知道效率不高,但要求样本不超过500个,页面大小为25。

我怎样才能更有效地做到这一点?

最佳答案

public int GetPage(int orderId, int sampleId, int itemsPerPage)
{
    //protect against divide by zero
   if(itemsPerPage < 1)
      return 1;//or 0 if you want page index

  int index = _context.Set<Sample>()
                       .Where(s => s.OrderId == orderId && s.Id < sampleId)
                       //.OrderBy(s => s.Id) edited after accepted OrderBy not necessary
                       .Count();

   //if index is zero return 1
   //if index == 9 and itemsPerPage == 10 return 1 
   //if index == 10 and itemsPerPage == 10 return 2
   //if you want the page index rather than the page number don't add 1
   return 1 + (index / itemsPerPage);
}

@Rob Lyndon 的努力让我想得更多,我想出了这种方法来检查页面是否实际包含示例 - 在对数据库的一次查询中

public int GetPage(int orderId, int sampleId, int itemsPerPage)
{
    //protect against divide by zero
   if(itemsPerPage < 1)
      return 1;//or 0 if you want page index, or -1 if you want to flag this as invalid

   var result = context.Set<Sample>()
                .Where(s => s.OrderId == orderId 
                            && s.Id <= sampleId)//this time include sampleId
                //.OrderBy(s => s.ID)  edited after accepted OrderBy not necessary
                .GroupBy(x => true)
                .Select(group => new
                {
                    MaxID = group.Max(s => s.Id),
                    Count = group.Count()
                })
                .Single();

  //Check the sample is actually in the result
  if(result.MaxID != sampleId)
      return 1;//or 0 if you want page index, or -1 if you want to flag this as invalid

  int index = result.Count - 1;

   //if you want the page index rather than the page number don't add 1
   return 1 + (index / itemsPerPage);
}

关于c# - 找出项目在哪个页面上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19931830/

相关文章:

c# - 压缩文件夹后所有 zip 条目更改编码

c# - LINQ 从字典中获取第一项不为空或为空

c# - 使用 LINQ 获取列表的前 N%

c# - 分层架构中的 Entity Framework ?

c# - Entity Framework - C# 或 VB.Net

c# - 数组组合的数组

c# - 数据库错误 : There is no row at position 0

c# - 作为.NET初学者,我应该学习什么,在哪里可以找到开源项目?

c# - 帮助对 Except 扩展方法进行新的覆盖

c# - 将新对象添加到 DbContext 时 Entity Framework 中出现空引用异常