c# - 使用 linq with join 在两个表上使用两个 where

标签 c# linq

我正在使用 Csharp Linq 创建以下报告

我有如下两张表


#Users
nid     pid     name
1       1       name1
2       1       name2

#Transactions
nid     tid     location    dcode 
1       T1      L1          D1
2       T1      L2          D1
2       T2      L1          D1
2       T2      L3          D1

The report contains


    a) columns from users table where nid != pid
    b) columns from transactions where tid == T2 and nid = results from a)
    c) the combination can have only one top row  in result 

nid     name        tid     Location
2       name2       T2      L1

the second record will not be present
- 2     name2       T2      L3

I have tried the following, using join

var report = (from u in users where u.nid != u.pid
                      join t in transactions
                      where t.tid == "T2"
                      on u.nid equals t.nid
                      select new 
                      {
                        // the report columns
                      }).Distinct().ToList();

在第二个“哪里”显示错误

谢谢你的帮助

最佳答案

交换查询的过滤和连接部分,并将 tid 重命名为 t.tid 或其他所需的过滤子句(在您的示例中,结果表确实有与 的交易tid == "T1",但您尝试使用 T2 进行过滤):

var report = (from u in users     
              join t in transactions 
              on u.nid equals t.tid     //<-- this line should precede 
              where t.tid == "T2"       //<-- this one
              && u.nid != u.pid
              select new 
              {
                    // the report columns
              }).Distinct().ToList();

Join 部分不能分开,所以在用 on 子句完成 join 之前不能写 where

关于c# - 使用 linq with join 在两个表上使用两个 where,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16789031/

相关文章:

c# - 从 C# 调用 powershell 脚本文件 (example.ps1)

c# - 调用带有 namespace 前缀的 SOAP 方法

c# - 在大列表中找到彼此接近的点

c# - 查询执行计划 - Where 子句何时执行?

c# - 如果结果为 NULL,LINQ 会在 Any() 上出错

c# - 使用 Linq 将进程名称与 XML 列表进行比较

c# - 我应该如何在 C# 中计算文件哈希 (md5 & SHA1)

c# - 在联接的基本 LINQ 查询上使用 lambda 表达式

sql-server - 在 LINQ 查询中使用 DateTime?.Value.TimeOfDay

c# - 通过等待每个任务异步转换 IEnumerable<Task<T>>