我在我的应用程序中使用带有 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/