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

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

我的问题是:

我有代码(在本例中我使用剃须刀代码):

@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();

问题是:

if (x => x.OfferProductId == offerProduct.OfferProductId) returns null ,代码将无法 select "BookAmount" 值并将抛出"Object reference not set to an instance of an object error."

我会写:

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())

您可以像这样创建自定义 HTML 助手:

Use ForEach extension in Razor

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>")