如何在查询中更改值

时间:2013-06-17 14:47:32

标签: c# linq

如何更改查询中的值,如下所示:

        return (from cust in entities.vw_WebCustomer
                where cust.CorporationId == token.CorporationId &&
                      cust.Branch == branch &&
                      cust.AccountNumber == accountnumber
                select new CustomerRequest
                         {
                           AccountId = cust.AccountId,
                           AccountNumber = cust.AccountNumber,
                           AreaCode = cust.AreaCode,
                           Branch = cust.Branch,
                           BudgetBalance = (decimal) cust.BudgetBalance,
                           BudgetRate = (decimal) cust.BudgetRate,
                           CareOf = cust.CareOf,
                           City = cust.City,
                           CurrentBalance = (decimal) cust.CurrentBalance,
                           CurrentTankPercentage = (decimal) cust.PercentFull, 
};

如果cust.PercentFull小于零,我想检查CurrentTankPercentage的值为零。

我是否必须拆开它才能对其进行更改?

2 个答案:

答案 0 :(得分:8)

最简单的方法是使用条件运算符:

select new CustomerRequest
 {
   ...
   CurrentTankPercentage = (decimal) (cust.PercentFull < 0 ? 0 : cust.PercentFull) 
 };

另一种方法是使用Math.Max

select new CustomerRequest
 {
   ...
   CurrentTankPercentage = (decimal) Math.Max(cust.PercentFull,0) 
 };

但我发现更难阅读。我倾向于误读为“给CurrentTankPercentage最大值0”,这与它的实际情况相反。

答案 1 :(得分:1)

您可以尝试:

CurrentTankPercentage = ((decimal)cust.PercentFull) < 0 ? 0 : ((decimal)cust.PercentFull)