gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:41:18 24 4
gpt4 key购买 nike

我正在使用 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;
}

关于c# - 如何使用可能的空列表处理此 LINQ 代码中的空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19169697/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com