C# mvc 使用 List where 条件,即使有 对象引用未设置为对象 errir 的实例

C# mvc use List where condition even if there are Object reference not set to an instance of an object errir

提问人:Yaniv Kriachko 提问时间:2/10/2019 最后编辑:ℍ ℍYaniv Kriachko 更新时间:2/10/2019 访问量:1143

问:

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

我的问题是:

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

@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 == offerProductProductId) 返回 null ,则代码将无法选择“BookAmount”值,并将抛出“对象引用未设置为对象的实例”错误。

我可以写:

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

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

这将起作用..

但我的问题是:

有没有选择不使用“foreach”和“if”子句(即使没有任何变量),只使用一行代码, 所以它会忽略空结果吗?

例如:

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

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

C# ASP.NET-MVC 列表 Razor NullReferenceException

评论


答:

0赞 wata 2/10/2019 #1

您可以创建自定义 HTML 帮助程序,如下所示:

在 Razor 中使用 ForEach 扩展

public static MvcHtmlString ForEach<T>(this IEnumerable<T> source, Func<T, Int32, string> selector)
{
    return new MvcHtmlString(String.Join("\n", source.Select(selector)));
}    

你可以在cshtml中这样写:

@Model.AccountingOfferAmountList.Where(x => x.OfferProductId == offerProduct.OfferProductId).ForEach((x,i) => $"<span>{x.BookAmount}</span>")