Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LINQ instead of using for-each loop

Tags:

c#

.net

linq

I have the following code. How to convert this into a LINQ? Any one please help me.

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

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;
    }
}

Thanks.

like image 565
Bhaskar Avatar asked Apr 21 '26 11:04

Bhaskar


1 Answers

So all you're trying to work out is whether any item has an update? That's just:

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

I've changed the comparison to just use a direct < rather than a subtraction and a comparison with 0, but this should be okay.

like image 165
Jon Skeet Avatar answered Apr 22 '26 23:04

Jon Skeet