简体   繁体   中英

LINQ Join (Left Outer) with Take(1)

I have the below LINQ that is returning zero IF there aren't any Addresses(Inner Join). How would I make this an Outer Join and then only Take(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();

Use 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
    });
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)
         }  

)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM