如果不匹配,LINQ连接表的值

时间:2016-09-02 21:50:33

标签: c# sql linq join

我知道有一些例子但我不能在我的代码上应用它们。我对Linq和SQL很新。我有两张桌子要加入。

第一张表:

--------------
| Id | Count |
--------------
| 1  |   10  |     
--------------
| 2  |   4   |               
--------------

第二张表:

--------------
| Id |  Name |
--------------
| 1  |  Tom  |     
--------------
| 2  |  John |               
--------------
| 3  |  Nick |               
--------------
| 4  |  Max  |               
--------------

如您所见,第二个表的记录多于第一个表。我的目标是根据Id加入他们。问题是,在我加入表后,它只显示匹配的记录,即Id 1和2.虽然我想显示每个Id(从1到4),如果两个表中都没有匹配,那么应该有默认值为0。

它应该是这样的:

----------------------
| Id |  Name | Count |
----------------------
| 1  |  Tom  |   10  |
----------------------
| 2  |  John |   4   |      
----------------------
| 3  |  Nick |   0   |      
----------------------
| 4  |  Max  |   0   |      
----------------------

到目前为止,我已经得到了这段代码:

// first table
var listCount = entity.tblKundes.Where(x => x.Studio == 2)
                                .Select(x => new { x.Id, x.Name})
                                .GroupBy(x => x.Name).ToList(); 

// second table
var listBerater = entity.tblUsers.Where(x => x.Studio == 2)
                                 .Select(x => new { x.Id, x.Name})
                                 .ToList();

// This join should be edited so that it displays non matching records as well
var test = listCount.Join(
     listBerater,
     count => count.Key,
     berater => berater.Id,
     (count, berater) => new { listCount = count, listBerater = berater }
).ToList();

修改

var test2 = (from list in listCount
             join berater in listBerater on list.Berater equals berater.Id into gj
             from sublist in gj.DefaultIfEmpty()
             select new { sublist.Id, sublist.Nachname, sublist.Vorname }).ToList();

1 个答案:

答案 0 :(得分:0)

在每个结构化查询语言中都有一个典型的概念叫做#34;左连接"。 Left-Join意味着您将拥有第一个表中的所有数据行,即使第二个表中没有等效数据。 "内加入"有点不同,只查找匹配的数据行。

在这里,您可以找到有关您的问题的足够和完整的信息。 Left Join

相关问题