【问题标题】:Use LINQ let with null return values使用带有空返回值的 LINQ let
【发布时间】: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;
}

这会引发错误,因为:如果 resultnulllet 不允许访问 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


【解决方案1】:

为什么不直接返回默认值而不是 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
             };

【讨论】:

  • 谢谢,我知道这应该可行,但在我的场景中,我返回一个模型(数据库表),我不能使用新的默认类型,因为它会在表中创建一个条目。任何其他可能涉及更改 linq 查询的解决方法?
  • 您正在从数据库中选择一个水果。这是你指的模型吗?选择它后,您会将其转换为匿名类型(即new {..} 部分)。我的回答与您原来的解决方案具有相同的效果。我在您的问题中没有看到任何update...
猜你喜欢
  • 2012-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-09
  • 1970-01-01
  • 2020-12-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多