簡體   English   中英

LINQ通過Take(左外)加入(1)

[英]LINQ Join (Left Outer) with Take(1)

如果沒有任何地址(內部聯接),我將在下面的LINQ中返回零。 我如何將其設置為外部聯接,然后僅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();

使用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)
         }  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM