【发布时间】:2016-05-20 18:34:04
【问题描述】:
我正在尝试在 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;
}
这会引发错误,因为:如果 result 是 null,let 不允许访问 type.Name,即使它是在 not null 检查之后。
有什么解决方法吗?
【问题讨论】:
-
你能发一个minimal reproducible example吗?另外,请发布实际的错误消息和异常类型。
-
这是 EF 还是 Linq to Objects?
-
我不认为您发布的代码准确地代表了您遇到问题的代码。我创建了一个代表您上面代码的小提琴,它工作得很好。 dotnetfiddle.net/goKgRx
-
如果你使用 c# 6,你也可以只做
type = GetType(fruit)?.Name ?? "N/A" -
谢谢@EricLippert 这是虚拟代码:D
标签: c# .net asp.net-mvc linq let