Skip to main content
 首页 » 编程设计

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

2024年02月13日15xiaohuochai

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

我有一些 Razor 代码,其中包含一些 LINQ。它试图从列表中获取值。有时列表为空。目前,应用程序正在引发空异常,即“myCustomers”为空。

代码:

Model.myCustomers.First().Name 

基本上“myCustomers”定义为:

public List<Customer> myCustomers 

并由“LINQ to Entity”查询填充。

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

Model.myCustomers.First().Name 

某种程度上。

希望这个问题不会太困惑!

非常感谢。

编辑 1

我喜欢不返回空值但返回空列表的逻辑。我尝试使用类似

return this._myCustomers ?? Enumerable.Empty<Customers>().ToList();  

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

编辑 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) 

请您参考如下方法:

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

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

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