简体   繁体   English

如何使用 LINQ 和 Where 条件连接两个数据表?

[英]How to JOIN two data tables using LINQ and Where condition?

I have two data tables as following我有两个数据表如下

    TableA      TableB
    UID         QID
    QID         Value1
                Value2

I want to join two data tables and get Value1 and Value 2. I tried the following, but I am not getting any data back.我想加入两个数据表并获取 Value1 和 Value 2。我尝试了以下操作,但没有得到任何数据。

string str = "AAA";
var result = (from t1 in TableA.AsEnumerable()
    //join between two tables
    join t2 in TableB.AsEnumerable() on t1.Field<string>("UID") equals t2.Field<string>("QID")
    //where conditions
    where t2.Field<string>("QID") == str && t1.Field<string>("QID") == "ABCD"
    //select clause
    select t2.Field<string>("Value1"));

This is my query with out using LINQ and its working.这是我没有使用 LINQ 及其工作的查询。

  Select t2.Value1, t2.value2 from  TableA t1 JOIN  TableB t2  ON t2.QID = t1.UID WHERE t2.QID = 'AAAAA' AND t1.QID = 'XXXX'

Thanks for your help.谢谢你的帮助。

Your LINQ code should work, I guess you just need to use the same where the condition values for QID .您的 LINQ 代码应该可以工作,我想您只需要使用与QID的条件值相同的地方。

 where t2.Field<string>("QID") == "AAA" && t1.Field<string>("QID") == "ABCD"

is not equal to your SQL:不等于您的 SQL:

 WHERE t2.QID = 'AAAAA' AND t1.QID = 'XXXX'

It should work when you set correct values in LINQ当您在 LINQ 中设置正确的值时,它应该可以工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM