【问题标题】:If and else statement with linq带有 linq 的 if 和 else 语句
【发布时间】:2013-02-18 08:33:53
【问题描述】:

我正在尝试在我的 linq 查询中使用 if 和 else 语句,但我无法显示正确的结果,您可以在下面看到部分代码:

from c in dc.Train_TBLs select new {c.CodeTrain,
DBL1 = (from u in dc.Train_NormalRate_TBLs where u.CodeTrainID == c.CodeTrainID orderby u.NormalRateID ascending select u.DBL).First(),
TPL1 = (from u in dc.Train_NormalRate_TBLs where u.CodeTrainID == c.CodeTrainID orderby u.NormalRateID ascending select u.TPL == (decimal?)null ? u.DBL / 2 * 3 == (decimal?)null : u.TPL != 0).First(),....}

在 TPL1 字段中,我的意图是显示“u.TPL”中的值等于“0”或 null 的情况,然后将字段“u.DBL”中的值除以 2 并乘以3 ,但我的代码不走运,那么您有什么建议如何显示正确的结果。

【问题讨论】:

  • 您是否尝试过将其还原为 foreach 循环并查看发生了什么问题?

标签: c# .net linq linq-to-sql


【解决方案1】:

我想这就是你想要的:

select ((u.TPL ?? 0) == 0 ? u.DBL / 2 * 3 : u.TPL)

用这个替换你最后的select

你说:

如果 "u.TPL" 中的值等于 "0" 或 null,则将从字段 "u.DBL" 中取值除以 2 并乘以 3

(u.TPL ?? 0) == 0 检查 u.TPL 是 0 还是 null。如果是,则返回u.DBL / 2 * 3,否则返回u.TPL 本身。此代码仅在u.TPL 可以为空(定义为decimal?)时才有效

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-20
    • 2019-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多