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

标签 c# c#-4.0

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

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

但我收到“对象未设置为对象的实例”错误。我需要使用 .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;
}

关于c# - 序列不包含匹配元素错误使用 bool ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29639396/

相关文章:

c# - C#插入语句-数组作为SQL列名

c#-4.0 - Entity Framework 核心 2.1 : The specified field 'Model' could not be found for property 'Model' on entity type 'BarCodeDevice'

c#-4.0 - 如何在没有匿名类型的情况下按多个字段进行 LINQ 区分

c# - 在 where 子句中组合两个 LINQ 条件

c# - 将 JSON 对象反序列化为 .NET HashSet

c# - 从多列 ListView 中删除选定的行

c# - 如何在 C# 中表示共轭表

c# - 使用数据库中的值加载 DataGridView 中的指定列

visual-studio-2010 - 如何在 C#.net 中为目标用户创建桌面路径

excel - 在 VSTO 中找不到从 XLStart 文件夹加载的所有插件