Retrieving an object's ID I have written the following Query to retrieve some object's ID. If there are objects in the list that have a larger numbinbatch than the saveditems number in the batch, then it should take that. If not, then it should take the first number from the lower number in batches.

I am wondering if this could be shortened. I'd also like to know if my query is bad for performance and how it can be improved.

int NextItemID = 0;
var items =
    rep.FindWhere(i =&gt; i.ID == itemID)
    .Select(i =&gt; i.Batch)
    .SelectMany(b =&gt; b.Items);

    var savedItem = items.First(i =&gt; i.ID == itemID);
    var unsavedItems = items.Where(i =&gt; i.StatusID == (short) ItemStatus.Pending);

    var higherNumInBatch = unsavedItems.Where(i =&gt; i.NumInBatch &gt; savedItem.NumInBatch).OrderBy(i=&gt;i.NumInBatch);
    var lowerNumInBatch = unsavedItems.Where(i =&gt; i.NumInBatch &lt; savedItem.NumInBatch).OrderBy(i=&gt;i.NumInBatch);

    if (higherNumInBatch.Any())
    {
       NextItemID = (int)higherNumInBatch.Take(1).First().ID;
    }
    else
    {
       NextItemID = (int)lowerNumInBatch.Take(1).First().ID;
    }

    return NextItemID;
This will be shorter, it takes less selects, and may runs at SQL server side

return rep.FindWhere(i =&gt; i.ID == itemID)
          .SelectMany(i =&gt; i.Batch.Items)
          .Where(i =&gt; i.StatusID == (short) ItemStatus.Pending)
          .MaxBy(i =&gt; i.NumInBatch).ID;