【问题标题】:Linq nested Join from a group join if null如果为 null,则从组加入 Linq 嵌套加入
【发布时间】:2013-09-04 01:41:52
【问题描述】:

我确信这很简单,但我一生都找不到这样的例子。

我正在对一个表进行组加入,然后我想对该分组加入进行第二次加入。

表 1 订单 表 2 联系人 表 3 电话号码

dim query = from order in Orders _
Group Join contact in Contacts On order.contactId equals contact.contactId Into grpContacts = Group From gcontact in grpContacts.DefaultIfEmpty()
Group Join phone in PhoneNumbers On phone.phoneNumberId Equals gcontact.homePhoneId Into grpPhoneNumbers = Group from gphone in grpPhoneNumbers.DefaultIfEmpty()

当 gcontact 为空时,此查询将在最后一次连接时出错。这是有道理的......但是如果记录不存在,我怎么做这个连接并且只有空/无值?

更新已解决 * 如果其他人遇到这种情况,您可以在 ON 运算符之后添加一个表达式,以确定之前的组加入是否为空。谢谢moander!

dim query = from order in Orders _
Group Join contact in Contacts On order.contactId equals contact.contactId Into grpContacts = Group From gcontact in grpContacts.DefaultIfEmpty()
Group Join phone in PhoneNumbers On IF(phone is nothing, 0, phone.phoneNumberId) Equals gcontact.homePhoneId Into grpPhoneNumbers = Group from gphone in grpPhoneNumbers.DefaultIfEmpty()

【问题讨论】:

    标签: vb.net linq join


    【解决方案1】:

    尝试使用iif避免在gcontact为null时访问:

    Equals iif(gcontact is nothing, 0, gcontact.homePhoneId)
    

    【讨论】:

    • 求求你,千万不要使用iff。请改用if。 if 是一个运算符,通常应该优先于 iff(这是一个函数),因为它提供了短路评估。如果你使用iff(它总是评估它的所有三个参数),那么NullReferenceException 将被抛出,因为gcontact.homePhoneId 将被评估。
    • 做到了!太感谢了!我不认为我可以在 Join 子句中添加一个表达式,这非常有效。我将更新问题以显示工作示例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2016-10-15
    • 2011-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多