如何使用foreach代替Join函数?

时间:2019-02-25 11:02:57

标签: c# asp.net-mvc model-view-controller

我想将此join操作转换为foreach,因为仅当Incoming product的{​​{1}}和materialIddepotId匹配时,此操作才有效的outgoing productmaterialId。但是,如果没有与进货相同物料和仓库ID的任何进货产品,我只想显示到库存页面的进货数量。 因此,我应该做一个foreach循环depotId并检索它匹配的支出总计,以在incomingProductTotals内完成其余的工作。但是我不能。

foreach

1 个答案:

答案 0 :(得分:0)

        var incomingProductTotals = Model.IncomingProduct
        .GroupBy(x => new { x.depotId, x.materialId })
        .Select(g => new
        {
            g.Key.materialId,
            g.Key.depotId,
            total = g.Sum(t => t.amount)
        });

        // retrieve all outgoing product totals (with materialId, depotId and total)
        var outgoingProductTotals = Model.OutgoingProduct
        .GroupBy(x => new { x.depotId, x.materialId })
        .Select(g => new
        {
            g.Key.materialId,
            g.Key.depotId,
            total = g.Sum(t => t.amount)
        });

        foreach(var inProduct in incomingProductTotals)
        {
            var outProduct = outgoingProductTotals.where(p => p.materialId == inProduct.materialId && p.depotId == inProduct.depotId).FirstOrDefault();
            if(outProduct != null)
            {
               <tr>
                   <td> @inProduct.materialId </td>
                   <td> @inProduct.depotId </td>
                   <td> @(inProduct.Total - outProduct.Total)</td>
               </tr>
             }

         }