【问题标题】:Can we use if statement in linq for deciding to join or not?我们可以在 linq 中使用 if 语句来决定是否加入吗?
【发布时间】:2014-08-05 11:21:26
【问题描述】:

我想在 Linq 的某些条件中包含一个表格。

我正在寻找这样的东西:

var query = from x in context.Messages 
if(x.senderID != 0)
{
    join et in context.ETs on x.senderID equals et.ID
}
where x.Getter == SSN
select new { x.id, x.message}

这种方法是否可行,还是我必须编写两个不同的 linq 查询然后将它们组合起来?

【问题讨论】:

  • 为什么不试试左外呢?我认为它适用于组加入并使用默认值。
  • 对于 确实 的 senderID 为 0 的项目,您希望得到什么结果?他们不应该出现在结果中吗?如果是这样,请在连接之前放置一个 where 子句...

标签: c# sql linq linq-to-sql linq-to-entities


【解决方案1】:
var query = from a in context.Messages
    join b in context.ETs
    on a.senderID equals b.ID
    into temp
    from b in temp.DefaultIfEmpty()
    where a.Getter == SSN
    select new { a.id, a.message}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-23
    • 1970-01-01
    • 1970-01-01
    • 2021-04-10
    • 2013-07-01
    • 1970-01-01
    相关资源
    最近更新 更多