简体   繁体   English

序列不包含匹配元素使用布尔值时出错

[英]Sequence contains no matching element Error using Boolean

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

This Ling query is giving me "Sequence contains no matching element" but I know I can use .FirstorDefault() . 这个Ling查询给我“序列不包含匹配的元素”,但是我知道我可以使用.FirstorDefault() When I use .FirstorDefault() it will return me false , the default value for bool , when there are no matching records. 当我使用.FirstorDefault()时,如果没有匹配的记录,它将返回false ,这是bool的默认值。

But I get a "Object not set to an instance of an object" error. 但是出现“对象未设置为对象的实例”错误。 I need to check the bool for null with .HasValue and .Value . 我需要使用.HasValue.Value检查bool是否为null I don't know how to do it. 我不知道该怎么做。

Here is how you can use a nullable bool to solve this: 这是您可以使用可为空的布尔来解决此问题的方法:

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;
}

You could do:- 您可以这样做:

bool? postkey = threadPostList
       .Where(x=>x.ThreadKey == threadKey && x.ClassKey == classKey)
       .Select(x => (bool?)x.PostKey)
       .DefaultIfEmpty()
       .First();

I think that better captures the intent of what you are trying to accomplish. 我认为这更好地体现了您想要实现的目标。

If you want to treat a null value as false (and don't want to use a nullable bool), you could just check if the resulting post is null before referencing the .PostKey property, like this: 如果要将null值视为false(并且不希望使用可为null的布尔值),则可以仅在引用.PostKey属性之前检查结果是否为null,如下所示:

var threadPost = statement.ThreadPostlist.FirstOrDefault(x => 
    x.ThreadKey == ThreadKey && x.ClassKey == classKey);

bool PostKey = threadPost != null && threadPost.PostKey;

Or, a longer form would be: 或者,更长的形式是:

bool PostKey;

if (threadPost != null)
{
    PostKey = threadPost.PostKey;
{
else
{
    PostKey = false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM