Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre><code>public int GetPage(int orderId, int sampleId, int itemsPerPage) { //protect against divide by zero if(itemsPerPage &lt; 1) return 1;//or 0 if you want page index int index = _context.Set&lt;Sample&gt;() .Where(s =&gt; s.OrderId == orderId &amp;&amp; s.Id &lt; sampleId) //.OrderBy(s =&gt; 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); } </code></pre> <p>@Rob Lyndon's effort made me think some more, and I came up with this as a way of checking that the page actually contains the sample - in one query to the database </p> <pre><code>public int GetPage(int orderId, int sampleId, int itemsPerPage) { //protect against divide by zero if(itemsPerPage &lt; 1) return 1;//or 0 if you want page index, or -1 if you want to flag this as invalid var result = context.Set&lt;Sample&gt;() .Where(s =&gt; s.OrderId == orderId &amp;&amp; s.Id &lt;= sampleId)//this time include sampleId //.OrderBy(s =&gt; s.ID) edited after accepted OrderBy not necessary .GroupBy(x =&gt; true) .Select(group =&gt; new { MaxID = group.Max(s =&gt; 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); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload