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 => i.ID == itemID)
.Select(i => i.Batch)
.SelectMany(b => b.Items);
var savedItem = items.First(i => i.ID == itemID);
var unsavedItems = items.Where(i => i.StatusID == (short) ItemStatus.Pending);
var higherNumInBatch = unsavedItems.Where(i => i.NumInBatch > savedItem.NumInBatch).OrderBy(i=>i.NumInBatch);
var lowerNumInBatch = unsavedItems.Where(i => i.NumInBatch < savedItem.NumInBatch).OrderBy(i=>i.NumInBatch);
if (higherNumInBatch.Any())
{
NextItemID = (int)higherNumInBatch.Take(1).First().ID;
}
else
{
NextItemID = (int)lowerNumInBatch.Take(1).First().ID;
}
return NextItemID;