使用可空的

时间:2014-07-07 10:36:43

标签: c# linq

我想从下面的代码中最小化if block。请帮我合适的扩展方法

               var v = (from rec in _DataContext.tblCourierMasters
                     where rec.CourierReceievedDate == dtCourierReceivedDate
                           && rec.RegionId == lRegionId
                           && rec.PODNumber == strPODNo
                     select new { rec.TotalCafReceived, rec.ReceiptDoneCount }).FirstOrDefault();

            lTPC = (long)v.TotalCafReceived;
            if (v.ReceiptDoneCount== null) {
                lRDC = -1;
            }
            else
                lRDC = (long)v.ReceiptDoneCount;

1 个答案:

答案 0 :(得分:2)

您可以使用null-coalescing operator

lDRC = (long)(v.ReceiptDoneCount ?? -1);

因此,如果v.ReceiptDoneCount为空,则lDRC将被赋予-1的值。

这是demo