找出项目所在的页面

Mer*_*wan 15 c# linq 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;
}
Run Code Online (Sandbox Code Playgroud)

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

public int GetPage(int orderId, int sampleId, int itemsPerPage)
{
    // ???
}
Run Code Online (Sandbox Code Playgroud)

我正在努力寻找在LINQ中做到这一点的方法.我现在唯一的想法就是一次又一次地获取页面,直到我找到所需的样本.我知道它效率不高但要求是样本不超过500个,页面大小为25.

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

Col*_*lin 3

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);
}
Run Code Online (Sandbox Code Playgroud)

@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);
}
Run Code Online (Sandbox Code Playgroud)