【发布时间】:2017-01-11 02:05:24
【问题描述】:
我知道有一些示例,但我无法将它们应用到我的代码中。我对 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();
【问题讨论】:
-
感谢您的回答。你能看看我的编辑吗?我必须删除 rder 中的分组才能加入它们,就像在 msdn 的示例中一样。你能帮我按名字分组吗?
-
收到答案后,您不应更改基本问题。你问如何做外部连接,它得到了回答。现在你问如何进行分组。如果您在互联网上找到(大量)示例后无法弄清楚,您应该为此提出一个新问题。也许接受对您最有帮助的答案。