c# - 将 LINQ let 与 null 返回值一起使用

标签 c# .net asp.net-mvc linq let

我正在尝试在 LINQ 中执行一个方法

var result = from fruit in fruits
             let type = GetType(fruit)
             select new {
                 fruit = fruit,
                 type = type != null ? type.Name : "N/A"
             };

FruitType GetType(Fruit fruit)
{
    if (fruit == a)
      return TypeA;
    else 
      return null;
}

这会引发错误,因为:如果 resultnull,则 let 不允许访问 type.Name 即使它是在 not null 检查之后。

有什么解决方法吗?

最佳答案

为什么不只返回一个默认值而不是 null?

FruitType GetType(Fruit fruit)
{
    if(fruit == a)
        return TypeA;
    return new FruitType {Name = "N/A"};
}

那么你的查询就变成了...

var result = from fruit in fruits
             let type = Gettype(fruit)
             select new {
                 fruit = fruit,
                 type = type.Name
             };

关于c# - 将 LINQ let 与 null 返回值一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37353599/

相关文章:

c# - (OAuthException) 必须使用事件访问 token 来查询有关当前用户的信息

c# - WPF TabControl - 无法以编程方式选择选项卡

c# - 模拟(使用最小起订量)返回模拟对象的方法的正确方法?

c# - Visual Studio 窗体设计器源代码的运行时创建

c# - 您如何检查写入目录或文件的权限?

asp.net-mvc - Azure Active Directory、OWIN 和 ASP .NET MVC

c# - 造成僵局

java - 反序列化 JSON 时如何删除或忽略 Java 类型提示?

asp.net-mvc - 为什么 Asp.NET MVC 优于 Asp.NET Web 窗体

asp.net-mvc - 将有用的消息从一个 Controller 传递到另一个重定向的 Controller