【发布时间】:2020-06-26 12:22:10
【问题描述】:
我是编写 Linq 查询的新手,想编写如下查询。
需求简介:
我需要为完全连接到另一个具有扩展数据的表的用户获取不同组键的计数
TABLE - 1: Table - 2:
--------------- -------------
| Id | GrpKey | prdId | UserId| | Id | GrpKey | GrpName | UserId
| 1 | 123455 | Test1 | 11111 | 1 | 123455 | GroupOne | 1111
| 2 | 123455 | Test2 | 22222 | 2 | 551234 | GroupTwo | 1111
| 3 | 123455 | Test3 | 22222 | 3 | 233344 |GroupThree| 1111
| 4 | 551234 | Test4 | 11111 | 4 | 278344 |GroupFour | 1111
| 5 | 551234 | Test5 | 11111
| 6 | DBNULL | Test4 | 11111
| 7 | DBNULL | Test5 | 11111
REQD. RESULT for UserId : 11111
--------------------------------
GrpKey | GrpName | Count(GrpKey)
DBNULL | DBNULL | 2
551234 | GroupTwo | 2
123455 | GroupOne | 1
233344 | GroupThree | 0
278344 | GroupFour | 0
Queries Tried:
**LEFT JOIN:**
from item in table1
join grp in table2 on item.GrpKey equals grp.GrpKey into j1
from rt in j1.DefaultIfEmpty()
where item.UserId == "1111"
group rt by rt.GrpKey into g
select new Group
{
UserId = grp.userId
Count = j1.Count(),
Name = grp.GrpName,
Key = grp.GrpKey,
}).ToList();
**RIGHT JOIN:**
from grp in table2
join item in table1 on grp.GrpKey equals item.GrpKey into j1
where grp.UserId == "1111"
group grp by grp.GrpKey into g
select new Group
{
UserId = grp.userId
Count = j1.Count(),
Name = grp.GrpName,
Key = grp.GrpKey,
}).ToList();
result = LeftJoinResult.Union(RightJoinResult).ToList();
TriedQuery1 的问题:
使用上面的 LINQ 查询,我得到的结果集是:
GrpKey | GrpName | Count(GrpKey)
DBNULL | DBNULL | 2
551234 | GroupTwo | 2
123455 | GroupOne | 1
551234 | GroupTwo | 1
233344 | GroupThree | 1
278344 | GroupFour | 1
请帮助我如何将此左联接转换为完全联接或数据,如 Reqd 结果中的那样
提前致谢
【问题讨论】:
-
先做左连接,再做右连接,然后取两者的并集
-
这是实现它的唯一方法吗?当我尝试实现联合时,存在重复行
-
不,联合不会产生重复
-
这能回答你的问题吗? LINQ - Full Outer Join
-
我尝试了正确的连接,但后来我在每一行中都算作一个
标签: c# .net entity-framework linq