LINQ加入(左外)与Take(1)

时间:2010-09-22 19:57:54

标签: c# .net linq linq-to-sql lambda

如果没有任何地址(内部连接),我有以下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();

3 个答案:

答案 0 :(得分: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 :(得分: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)
         }  

答案 2 :(得分:0)