【问题标题】:C# Linq: Select numeric columns that accepts nullC# Linq:选择接受 null 的数字列
【发布时间】:2012-11-24 14:35:12
【问题描述】:

我有强类型数据集。现在我想用 linq 对数据表进行选择。

我的问题是该表具有允许空值的数字列。但是,如果有数据行在此列中没有值,我不知道要执行 Select- 命令。

这是我的查询:

var query = from tab1 in localDataSet.simpleTable
            select new {
               line = tab1.IsLineNull ? null : tab1.line,
               wait = tab1.IswaitNull() ? null : tab1.wait
            }

如果 tab1.IsLineNull() 返回 true,我无法设置 line = null,因为数据类型“十进制”(以及所有其他数字值类型)不能为 null。但是我应该选择什么呢?我也不能选择0。

【问题讨论】:

  • 为什么所有数值类型都不能为空的时候,还要创建IsLineNull的方法?
  • @TimSchmelter 他们实际上可以使用'int'为空?或“双倍?”等等。也适用于 bool
  • 更改您的模型以使用可为空的类型。详情见这里; msdn.microsoft.com/en-us/library/1t3y8s4s(v=vs.80).aspx
  • @The_Cthulhu_Kid:我知道他们通常可以,但 OP 提到他们不能:“因为数据类型“十进制”(以及所有其他数字值类型)不能为空。 " 编辑:我认为 OP 会知道 nullables。

标签: c# linq ado.net dataset


【解决方案1】:

我假设你不知道如何创建Nullable<T>

var query = from tab1 in localDataSet.simpleTable
        select new {
           line = tab1.IsLineNull ?   new Nullable<decimal>(): tab1.line,
           wait = tab1.IswaitNull() ? new Nullable<decimal>(): tab1.wait
        }

【讨论】:

    【解决方案2】:

    你必须在你的 ? : 到 tab1.line 和 tab1.wait 的类型。

    var query = from tab1 in localDataSet.simpleTable
                select new {
                   line = tab1.IsLineNull ? (decimal?)null : tab1.line,
                   wait = tab1.IswaitNull() ? (decimal?)null : tab1.wait
                }
    

    【讨论】:

      【解决方案3】:

      放一个

      (int?) 
      

      (decimal?)
      

      null 之前,它将null 转换为可为空的整数/小数

      另外,如果你的方法:

      IsLineNull
      IswaitNull
      

      只要控制字段是否为空,就可以减少问题:

      var query = from tab1 in localDataSet.simpleTable
                  select new {
                     line = (int?)tab1.line,
                     wait = (int?)tab1.wait
                  }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-04-04
        • 2013-11-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-19
        • 2016-08-27
        相关资源
        最近更新 更多