序列不包含匹配元素错误使用布尔
Sequence contains no matching element Error using Boolean
bool Postkey =
statement
.ThreadPostlist
.First(x => x.ThreadKey == ThreadKey && x.ClassKey == classKey)
.PostKey;
这个 Ling 查询给了我 "Sequence contains no matching element" 但我知道我可以使用 .FirstorDefault()
。当我使用 .FirstorDefault()
时,它会 return 我 false
,当没有匹配记录时 bool
的默认值。
但是我收到 "Object not set to an instance of an object" 错误。我需要用 .HasValue
和 .Value
检查 bool
是否有 null
。我不知道该怎么做。
下面是如何使用可为 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;
}
你可以这样做:-
bool? postkey = threadPostList
.Where(x=>x.ThreadKey == threadKey && x.ClassKey == classKey)
.Select(x => (bool?)x.PostKey)
.DefaultIfEmpty()
.First();
我认为这样可以更好地捕捉您要完成的目标的意图。
如果您想将 null
值视为 false(并且不想使用可为 null 的布尔值),您可以在引用 .PostKey
属性,像这样:
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;
}
bool Postkey =
statement
.ThreadPostlist
.First(x => x.ThreadKey == ThreadKey && x.ClassKey == classKey)
.PostKey;
这个 Ling 查询给了我 "Sequence contains no matching element" 但我知道我可以使用 .FirstorDefault()
。当我使用 .FirstorDefault()
时,它会 return 我 false
,当没有匹配记录时 bool
的默认值。
但是我收到 "Object not set to an instance of an object" 错误。我需要用 .HasValue
和 .Value
检查 bool
是否有 null
。我不知道该怎么做。
下面是如何使用可为 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;
}
你可以这样做:-
bool? postkey = threadPostList
.Where(x=>x.ThreadKey == threadKey && x.ClassKey == classKey)
.Select(x => (bool?)x.PostKey)
.DefaultIfEmpty()
.First();
我认为这样可以更好地捕捉您要完成的目标的意图。
如果您想将 null
值视为 false(并且不想使用可为 null 的布尔值),您可以在引用 .PostKey
属性,像这样:
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;
}