我是编写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
| 4 | 551234 | Test4 | 11111
| 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
Queries Tried:
1)
from grp in table2
join item in table1 on grp.GrpKey equals item.GrpKey into j1
where grp.UserId == "1111"
select new Group
{
Count = j1.Count(),
Name = grp.GrpName,
Key = grp.GrpKey,
}).ToList();
2)
var result = (from item in table1
join grp in table2 on item.GrpKey equals grp.GrpKey into j1
from rt in j1.DefaultIfEmpty()
where item.userId == userId
select new Group
{
GrpKey = item.GrpKey,
userId = item.userId,
Count = j1.Count(),
GrpName = rt.GroupName
}).ToList();
通过上面的LINQ查询,我能够获得所有值的计数,但GrpKey和GrpName为空的行除外。 有没有人能帮我查询一下我所需要的数据集
即使存在值为null的行,但具有null或等于零的行的计数。
提前致谢
对于第二个查询,您可以为左连接结果添加Group by,如以下代码所示:
var result = (from item in table1
join grp in table2 on item.GrpKey equals grp.GrpKey into j1
from rt in j1.DefaultIfEmpty()
where item.userId == 11111
group rt by rt?.GrpKey into g
select new
{
GrpKey = g.Key,
GrpName = g.First()?.GrpName,
Count = g.Count(),
}).ToList();
我希望你觉得这对你有帮助。