2011-01-25 64 views
1

我有對象的列表,這些對象可能會或可能不會有聯絡信息:LINQ加入和羣組加入

  // Join contact 
     query = query.Join(
     (new ContactRepository(this.Db)).List().Where(x => x.IsMainContact), 
     x => new { x.ListItem.ContentObject.LoginId }, 
     y => new { y.LoginId }, 
     (x, y) => new ListItemExtended<ListItemFirm> 
     { 
      City = y.City, 
      State = y.State, 
      Country = y.Country 
     }); 

這確實內部聯接上「登錄ID」。但是我需要一個outter join,所以如果聯繫信息不存在給定的LoginId,它將是空的。 請幫助

感謝

回答

1

你應該執行外手動加入:

  var contacts = (new ContactRepository(this.Db)).List(); 
      query.Select(item => 
      { 
       var foundContact = contacts.FirstOrDefault(contact => contact.Id == item.Id); 
       return new ListItemExtended<ListItemFirm>() 
        { 
         Id = item.Id, 
         City = foundContact != null ? foundContact.City : null, 
         State = foundContact != null ? foundContact.State : null, 
         Country = foundContact != null ? foundContact.Country : null, 
        }; 
      }) 

但是請記住,如果你跟產品結構 - 檢查空是不妥當的辦法。使用Any()運算符而不是FirstOrDefault()。