开发者

Using LINQ instead of using for-each loop

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜