如何使用可能的空列表处理此LINQ代码中的空值?

时间:2013-10-03 21:38:43

标签: c# asp.net-mvc asp.net-mvc-3 linq linq-to-entities

我正在使用MVC3,Razor,C#。

我有一些Razor代码,其中包含一些LINQ。它试图从List中获取值。有时列表为空。目前,该应用程序因此提出了一个空例外,即“myCustomers”为空。

代码:

Model.myCustomers.First().Name

基本上“myCustomers”定义为:

public List<Customer> myCustomers

并填充“LINQ to Entity”查询。

如果“myCustomers”为null,我该如何确保剃刀代码不会崩溃。我不想为每个属性写很多“if(Name!= null)”类型块。由于布局设计问题,我无法遍历所有属性。所以我需要改变:

Model.myCustomers.First().Name

以某种方式。

希望这个问题不会太混乱!

提前多多感谢。

编辑1

我喜欢不返回空值的逻辑,而是空列表。我尝试过像

这样的东西
return this._myCustomers ?? Enumerable.Empty<Customers>().ToList(); 

理想的做法是在Razor页面的LINQ的一行中测试它是空的而不是在“IF”块中。

编辑2

    public static TValue SafeGet<TObject, TValue>(
        this TObject obj,
        Func<TObject, TValue> propertyAccessor)
    {
        return obj == null ? default(TValue) : propertyAccessor(obj);
    }

所以:

   Model.myCustomers.FirstOrDefault().SafeGet(m=>m.Name)

3 个答案:

答案 0 :(得分:2)

Collection or enumerable should never return null value for best practice.

一旦确定myCustomers不为null,您只需要检查myCustomers的第一项不是null。

var customer = Model.myCustomers.FirstOrDefault();
if (customer != null)
{
   var name = customer.Name;
}

答案 1 :(得分:1)

  

由于布局设计问题,我无法遍历所有属性。

我不清楚这意味着什么,但你不能做这样的事吗?

@if (Model.myCustomers == null || !Model.myCustomers.Any())
{
    <p>No customer found.</p>
}
@else
{
    [ put the markup for each property here ]
}

答案 2 :(得分:1)

如果您的收藏品不是null,那么您可以在razon视图中使用

 Model.myCustomers.Any() ? Model.myCustomers.First().Name : string.Empty;

如果由于某种原因你不能避免你的收藏为空,我猜你可以这样做。

 Model.myCustomers == null ? string.Empty : Model.myCustomers.Any() 
       ? Model.myCustomers.First().Name : string.Empty;