C#MVC使用列表WHERE条件,即使有对象引用不设置到对象errir的实例

问题描述 投票:-1回答:1

我已经搜索这个网站对于我的问题的答案,但没有找到:(

我的问题是:

我有一些代码(在这种情况下,我用剃刀代码):

@foreach (IAccountingOfferAmount accountingAmount in Model.AccountingOfferAmountList)
{
  if(offerProduct.OfferProductId == accountingAmount.OfferProductId)
  {
    <span>@accountingAmount.BookAmount</span>
  }
}

[上面的代码工作版本,并与没有问题)

这相当于

@Model.AccountingOfferAmountList
   .Where(x => x.OfferProductId == offerProduct.OfferProductId)
   .FirstOrDefault().BookAmount.ToString();

问题是:

如果(X => x.OfferProductId == offerProduct.OfferProductId)返回null,代码将不能够选择“BookAmount”值和将引发“对象引用不设置为一个对象错误的一个实例。”

我可以这样写:

var test =  Model.AccountingOfferAmountList
      .Where(x => x.OfferProductId == offerProduct.OfferProductId)
      .FirstOrDefault();

if(test != null)
{
  <span>@test.BookAmount.ToString()</span>
}

这将工作..

但我的问题是:

是否有任何选项不使用“的foreach”和“如果”的条款(即使没有任何变量),只需使用一行代码,因此它会忽略空的结果吗?

例如:

@Model.AccountingOfferAmountList.Where(x => x.OfferProductId == offerProduct.OfferProductId)
    .DefaultIfNull(String.Empty)
    .FirstOrDefault().BookAmount.ToString(); 

(不工作例子当然只是如果万一变空,会有打印“”,不会继续.FirstOrDefault()的想法。BookAmount.ToString())

c# asp.net-mvc list razor nullreferenceexception
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.