Linq与LEFT加入

时间:2013-02-10 14:32:10

标签: c# linq

        var query =
            (from Contact con in e.Results
             from ContactPhoneNumber phn in con.PhoneNumbers
             from ContactEmailAddress email in con.EmailAddresses.DefaultIfEmpty()
             where con.DisplayName.Contains(txtContasctSearch.Text)
             select new person()
             {
                 displayName = con.DisplayName,
                 displayEmail = (email.EmailAddress == null ? String.Empty : email.EmailAddress),
                 displayPhone = phn.PhoneNumber
             }).ToList();

EmailAddress字段并非始终可用。但是,如果它存在,我仍然想把它带回来。我想模仿一个Left Join,但上面的代码会返回一个错误。

有什么想法吗?

我收到的错误是:

 System.NullReferenceException occurred
   _HResult=-2147467261
    _message=NullReferenceException
     HResult=-2147467261
    Message=NullReferenceException
    Source=wpChoreList
    StackTrace:
       at wpChoreList.personSetup.<Contacts_SearchCompleted>b__8(<>f__AnonymousType1`2    h__TransparentIdentifier1)
   InnerException: 

1 个答案:

答案 0 :(得分:2)

您正在检查null的错误值:

displayEmail = (email.EmailAddress == null ? String.Empty : email.EmailAddress),

电子邮件应为空,而不是email.EmailAddress,请尝试将该行更改为此行:

displayEmail = (email == null ? String.Empty : email.EmailAddress),