首页 > 解决方案 > Linq 查询以在多个条件下连接表 C#

问题描述

我是编写 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();


TriedQuery1 的问题:

使用上面的 LINQ 查询,我可以获得除 GrpKey 和 GrpName 为 NULL 的行之外的所有值的计数。任何人都可以帮我查询以根据我所需的数据集获取数据吗

TriedQuery2 的问题:

即使有值为 NULL 的行,具有 null 或为零的行数。

提前致谢

标签: c#entity-frameworklinq

解决方案


对于第二个查询,您可以为左连接结果添加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();

我希望你觉得这有帮助。


推荐阅读