c# - LINQ 函数中可空类型的问题

标签 c# linq linq-to-sql linq-to-objects nullable

Parent_ObjectiveIDidentityint? 数据类型。在我的程序中应该返回一个对象,但它给出了一个错误:Sequence contains no elements

int? identity = null;

Objective currentObjective = (from p in cd.Objective
                              where p.Parent_ObjectiveID == identity
                              select p).Single();

虽然,如果我将标识变量替换为 null。它有效,但我不明白。

currentObjective = (from p in cd.Objective
                    where p.Parent_ObjectiveID == null
                    select p).Single();

发生了什么事?

更新 1:

我这样做了:

if (identity == null)
{
     currentObjective = (from p in cd.Objective
                         where p.Parent_ObjectiveID == null
                         select p).Single();
}
else
{
     currentObjective = (from p in cd.Objective
                         where p.Parent_ObjectiveID == identity
                         select p).Single();
}

但我不是很喜欢。

最佳答案

LINQ 似乎不支持 where 子句中的这种情况。

This question是关于同样的问题。另见 this thread .

你可以试试:

Objective currentObjective = (from p in cd.Objective
                                  where p.Parent_ObjectiveID == (identity ?? null)
                                  select p).Single();

编辑:如果这不起作用,请尝试与 object.Equals 进行比较:

Objective currentObjective = (from p in cd.Objective
                                  where object.Equals(p.Parent_ObjectiveID, identity)
                                  select p).Single();

关于c# - LINQ 函数中可空类型的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7085713/

相关文章:

c# - Umbraco - 在 C# 中查找根节点

c# - 以通用方式测试匿名类型的字段值

c# - lambda 表达式使用 select 和 where 子句连接多个表

linq-to-sql - LINQ To SQL - 选择常量值

c# - 将 LinqDataSource 绑定(bind)到两个单独的表

linq-to-sql - 分组后的LINQ选择

c# - 如何强制应用程序不以管理员身份运行

c# - 从 UICommand/MessageDialog 启动 FilePicker 或 FolderPicker

c# - 在 C# 中返回状态代码或复杂对象的理想方法是什么?

c# - Linq group by 跨不同表的多个字段