Parent_ObjectiveID
和 identity
是 int?
数据类型。在我的程序中应该返回一个对象,但它给出了一个错误: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/