2010-09-22 109 views
2

我有以下LINQ返回零如果沒有任何地址(內部加入)。我如何使這個外部加入,然後只有Take(1)LINQ加入(左外)與拿(1)

var results = query.Join(
       DB.tblAddresses.Where(t => t.AddressTypeID == 'm' || t.AddressTypeID == 'b').OrderByDescending(x => x.AddressTypeID), 
       p => p.PersonID, 
       a => a.PersonID, 
       (p, a) => 
       new 
        { 
         p.PersonID, 
         p.LastName, 
         p.FirstName, 
         p.MiddleName, 
         p.SSN, 
         p.BirthDate, 
         p.DeathDate, 
         AddressLine1 = a.AddressLine1 ?? string.Empty 
       }); 

      return results.CopyLinqToDataTable(); 

回答

3

使用GroupJoin

var results = query.GroupJoin(
    addresses, 
    p => p.PersonID, 
    a => a.PersonID, 
    (p, a) => 
    new 
    { 
     p.PersonID, 
     p.LastName, 
     p.FirstName, 
     p.MiddleName, 
     p.SSN, 
     p.BirthDate, 
     p.DeathDate, 
     AddressLine1 = a.Any() 
      ? (a.First().AddressLine1 ?? string.Empty) 
      : null 
    }); 
1
query 
    .SelectMany ( 
     p => DB.tblAddresses.Where((t => t.AddressTypeID == 'm' || t.AddressTypeID == 'b') && t.PersonID == p.PersonID)**.DefaultIfEmpty()**, 
     (p, t) => 
     new 
     { 
      p.PersonID, 
         p.LastName, 
         p.FirstName, 
         p.MiddleName, 
         p.SSN, 
         p.BirthDate, 
         p.DeathDate 
      Addressline1 = (t == null ? null : t.AddressLine1) 
     } 

+0

對於每個「p」,「t」將是相同的,這不是想要的。另外,如果't'爲'null',則會拋出't.Addressline1'(如果在第二行生成的集合將爲空,則會發生這種情況)。 – svick 2010-09-22 20:21:54

+0

使用:Addressline1 =(t == null?null:t.AddressLine1) – Kamyar 2010-09-22 20:23:03

+0

是的,這解決了第二個問題,但第一個問題更大。 – svick 2010-09-22 20:26:38