简体   繁体   中英

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() . When I use .FirstorDefault() it will return me false , the default value for bool , when there are no matching records.

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 . 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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