使用带有 null 返回值的 LINQ let

use*_*799 1 .net c# linq asp.net-mvc 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;
}
Run Code Online (Sandbox Code Playgroud)

这会引发错误,因为: if resultis null,即使在检查之后也let不允许访问。type.Namenot null

有什么解决方法吗?

Cal*_*Kid 5

为什么不直接返回默认值而不是 null 呢?

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

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

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