如何在linq中使用“COALESCE(SUM ...”?

时间:2010-06-25 11:50:00

标签: c# .net visual-studio linq

我尝试使用sum和Coalesce。我怎样才能翻译成linq?

 SELECT @SumQtyOut=COALESCE(SUM(Qty),0) FROM dbo.StockMovement WHERE FromLocationType=@FromLocationType AND
         * FromNo=@FromNo AND FromSeq=@FromSeq AND ItemTypeNo=@ItemTypeNo AND ItemID=@ItemID

我做了些事:

 using (StockProcedureDataContext stock = new StockProcedureDataContext())
                {
                    SumQtyOut = from s in stock.StockMovements 
                                where s.FromLocationType == FromLocationType &&
                                s.FromNo== FromNo && 
                                s.FromSeq == FromSeq &&
                                s.ItemTypeNo == ItemTypeNo &&
                                s.ItemID == ItemID select 
                }

1 个答案:

答案 0 :(得分:0)

此代码段应该会产生您要查找的结果。

using (StockProcedureDataContext stock = new StockProcedureDataContext())
{
    var items = from s in stock.StockMovements 
                where s.FromLocationType == FromLocationType &&
                s.FromNo== FromNo && 
                s.FromSeq == FromSeq &&
                s.ItemTypeNo == ItemTypeNo &&
                s.ItemID == ItemID 
                select s.Qty ?? 0;
    SumQtyOut = items.Sum(x => x);
}
如果select s.Qty ?? 0s.Qty,则

null会返回0。 items.Sum(x => x)总结了您选择的数量。