Skip to main content
 首页 » 编程设计

c#之序列不包含匹配元素错误使用 bool

2024年02月06日13think

bool Postkey = 
    statement 
        .ThreadPostlist 
        .First(x => x.ThreadKey == ThreadKey && x.ClassKey == classKey) 
        .PostKey; 

此 Ling 查询显示“序列不包含匹配元素”,但我知道我可以使用 .FirstorDefault()。当我使用 .FirstorDefault() 时,当没有匹配的记录时,它会返回 false,bool 的默认值。

但我收到“对象未设置为对象的实例”错误。我需要使用 .HasValue 和 .Value 检查 bool 是否为 null。我不知道该怎么做。

请您参考如下方法:

下面是如何使用可为空的 bool 值来解决这个问题:

bool? postKey = null; 
// This can be null 
var post = statement.ThreadPostlist.FirstOrDefault(x=>x.ThreadKey == ThreadKey  && x.ClassKey == classKey); 
if (post != null) { 
    postKey = post.PostKey; 
} 
// Now that you have your nullable postKey, here is how to use it: 
if (postKey.hasValue) { 
    // Here is the regular bool, not a nullable one 
    bool postKeyVal = postKey.Value; 
}