开发者

Using LINQ instead of using for-each loop

开发者 https://www.devze.com 2023-03-06 08:20 出处:网络
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.

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);
开发者_如何学Python    decimal quantityToReceive = item.QuantityReceived - line.QuantityReceivedToDate;

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

Thanks.


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.


Untested, but this should do the same and 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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号