【问题标题】:How to check if int is not null如何检查int是否不为空
【发布时间】:2020-08-10 05:27:18
【问题描述】:

我正在尝试从数据库中获取数据,但我卡在了最后一行。 BestSellerRating 是 int,我不知道在这里做什么。我需要 bestSeleltRating 高于 0 而不是空值。 "表达式的结果始终为真,因为 int 类型的值永远不会等于 int 类型的 null"

var articles = (from a in _db.Articles
                join articleRating in _db.ArticleRatings on a.Id equals articleRating.ArticleId
                where a.IsDeleted == false
                      && a.IsFinished
                      && a.IsSubmited
                      && a.BestsellerRating > 0
                      && a.BestsellerRating != null

【问题讨论】:

  • BestSellerRating 的类型更改为int?,这意味着“可为空的int”,因此您可以分配并检查null
  • 除了 Alex 刚才所说的之外,您还可以检查 int? 上的 HasValue 属性,看看它是否为空。
  • 我没有在我的开发机器上快速尝试它......但是,如果你将一个 int 定义为可为空的 int?,你不能检查它是否为空?

标签: c#


【解决方案1】:

我需要 bestSeleltRating 高于 0 而不是空值 - 实际问题被问到。

他不是在问如何使 int 可以为空。

您在下面检查 a.BestsellerRating > 0 和 a.BestsellerRating != null。

您只需要 a.BestsellerRating > 0。它永远不会为空,并且此条件将始终检查它是否高于 0。

与此相反的是 a.BestsellerRating == 0

var articles = (from a in _db.Articles
            join articleRating in _db.ArticleRatings on a.Id equals articleRating.ArticleId
            where a.IsDeleted == false
                  && a.IsFinished
                  && a.IsSubmited
                  && a.BestsellerRating > 0
                  && a.BestsellerRating != null

【讨论】:

    【解决方案2】:

    数据库及其查询结果有不同的方式来注释 null,因此!= null 将不起作用。

    它可能因您使用的特定数据库和特定的数据库访问类集而异,但通常它映射到 DBNull 类:

    https://docs.microsoft.com/en-us/dotnet/api/system.dbnull

    当然,我们也在这里处理 LINQ,可能还有 LINQ to SQL,所以它可能又是完全不同的东西了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 2011-05-20
      • 1970-01-01
      • 2023-02-16
      • 1970-01-01
      相关资源
      最近更新 更多