Using LINQ instead of using for-each loop

I have the following code. How to convert this to LINQ? Anyone please help me.

In the code below, 'powd' contains db values, and purchaseOrderUpdateRequest contains user-submitted data.

bool hasUpdate;

foreach (var item in purchaseOrderUpdateRequest.Lines)
{
    var line = powd.PurchaseOrderLines.Single(p => p.ItemNumber ==  item.ItemNumber);
    decimal quantityToReceive = item.QuantityReceived - line.QuantityReceivedToDate;

    if (quantityToReceive > 0)
    {
        hasUpdate =true;
        break;
    }
}

Thank.

+3
source share
2 answers

So, all you are trying to decide is whether any item has an update? It's simple:

var hasUpdate = purchaseOrder.UpdateRequest.Lines.Any(item =>
     item.QuantityReceived < powd.PuchaseOrderLines
                                 .Single(p => p.ItemNumber == item.ItemNumber)
                                 .QuantityReceivedToDate)

I changed the comparison by simply using a straight line <rather than subtracting and comparing with 0, but that should be fine.

+13
source

Unconfirmed, but this should do the same and it might be easier to read:

   var quantities = (from item in purchaseOrderUpdateRequest.Lines
                     from item2 in powd.PurchaseOrderLines
                     where item.ItemNumber == item2.ItemNumber
                     select item.QuantityReceived - item2.QuantityReceivedToDate);
   hasUpdate = quantities.Any(quantityToReceive => (decimal) quantityToReceive > 0);
0
source

All Articles