gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:47:57 28 4
gpt4 key购买 nike

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com