3

我有以下查询,但我不知道如何在表 1 上进行左外连接。

var query = (from r in table1
             join f in table2
                 on r.ID equals f.ID
             select new
             {     
                 r.ID, 
                 r.FirstName,
                 r.LastName,
                 FirstNameOnRecord = 
                     (f != null ? f.FirstName : string.Empty),
                 LastNameOnRecord = 
                     (f != null ? f.LastName : string.Empty),
                 NameChanged = 
                     (f != null 
                         ? (f.FirstName.CompareTo(r.FirstName) == 0 
                             && f.LastName.CompareTo(r.LastName) == 0) 
                         : false)
             }).ToList();
4

4 回答 4

6

请参考示例以了解更多信息,您的情况将是这样的-

var query = from r in table1
            join f in table2
            on r.ID equals f.ID into g
            from f in g.DefaultIfEmpty()
             select new
             {     
                r.ID
                , r.FirstName
                , r.LastName
                , FirstNameOnRecord = (f != null ? f.FirstName : string.Empty)
                , LastNameOnRecord = (f != null ? f.LastName : string.Empty)
                , NameChanged = (f != null ? (f.FirstName.CompareTo(r.FirstName) == 0 
                &&  f.LastName.CompareTo(r.LastName) == 0) : false)
              }).ToList();
于 2010-10-19T17:41:01.720 回答
5

这是左外连接的一个很好的细分。

于 2010-10-19T17:38:42.080 回答
3

你见过这些例子吗?您可能对有关 Linq 中的 Left Outer Join 的这一部分感兴趣。

于 2010-10-19T17:38:52.267 回答
0

使用 lambda 表达式

db.Categories    
  .GroupJoin(
     db.Products,
     Category => Category.CategoryId,
     Product => Product.CategoryId,
     (x, y) => new { Category = x, Products = y })
  .SelectMany(
     xy => xy.Products.DefaultIfEmpty(),
     (x, y) => new { Category = x.Category, Product = y })
  .Select(s => new
  {
     CategoryName = s.Category.Name,     
     ProductName = s.Product.Name   
  })
于 2014-04-03T15:15:03.297 回答