我正在尝试在 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
检查之后。
有什么解决方法吗?
最佳答案
为什么不只返回一个默认值而不是 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/