[英]Sequence contains no matching element Error using Boolean
bool Postkey =
statement
.ThreadPostlist
.First(x => x.ThreadKey == ThreadKey && x.ClassKey == classKey)
.PostKey;
这个Ling查询给我“序列不包含匹配的元素”,但是我知道我可以使用.FirstorDefault()
。 当我使用.FirstorDefault()
时,如果没有匹配的记录,它将返回false
,这是bool
的默认值。
但是出现“对象未设置为对象的实例”错误。 我需要使用.HasValue
和.Value
检查bool
是否为null
。 我不知道该怎么做。
这是您可以使用可为空的布尔来解决此问题的方法:
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;
}
您可以这样做:
bool? postkey = threadPostList
.Where(x=>x.ThreadKey == threadKey && x.ClassKey == classKey)
.Select(x => (bool?)x.PostKey)
.DefaultIfEmpty()
.First();
我认为这更好地体现了您想要实现的目标。
如果要将null
值视为false(并且不希望使用可为null的布尔值),则可以仅在引用.PostKey
属性之前检查结果是否为null,如下所示:
var threadPost = statement.ThreadPostlist.FirstOrDefault(x =>
x.ThreadKey == ThreadKey && x.ClassKey == classKey);
bool PostKey = threadPost != null && threadPost.PostKey;
或者,更长的形式是:
bool PostKey;
if (threadPost != null)
{
PostKey = threadPost.PostKey;
{
else
{
PostKey = false;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.