【问题标题】:LINQ Case When Query查询时的LINQ案例
【发布时间】:2013-09-17 20:19:15
【问题描述】:

我在 Oracle SQL 语法中有一个如下所示的 SQL 查询,我希望它在 LINQ 中相等。

Select Case When tbl.Id=1 then 1 else NULL End as col1,
Case When tbl.Id=2 then 2 else NULL End as col2,
Case When tbl.Id=3 then 3 else NULL End as col3
From Table1 tbl

【问题讨论】:

  • 顺便说一句,您宁愿尝试一下,先生。

标签: c# .net sql linq oracle


【解决方案1】:

您可以在Select 中使用conditional operator

var result = 
    table1.Select(x => new
                       {
                           col1 = x.Id == 1 ? (int?)1 : null,
                           col3 = x.Id == 2 ? (int?)2 : null,
                           col3 = x.Id == 3 ? (int?)3 : null
                       });

【讨论】:

  • 你忘记了(int?)。 :p
  • @AgentFire:是的,在你的回答中看到了。现在修复:)
【解决方案2】:
var items = from item in Table1
            select new
            {
                 col1 = item.Id == 1 ? (int?)1 : null,
                 col3 = item.Id == 2 ? (int?)2 : null,
                 col3 = item.Id == 3 ? (int?)3 : null)
            };

【讨论】:

  • @ehsan 确实,我已经解决了这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-17
  • 2014-11-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多