2011-09-20 44 views
0
int id =2 ; 
(from t1 in Table1 
join t2 in Table2 
on new { t1.id, id} equals new { t2.id, t2.otherid } 
select t1).ToList(); 

目前上述查询给了我一个编译错误说如何正确重写这个linq查询?

的加入表现之一是不正确的类型。

正如你在上面的查询中看到的,我想在sql中加入一个整数值。我想要这些,以便查询更快,我不想在最后做一个地方,因为这意味着它将获得所有行,然后使用where子句进行筛选。因为我在这两个表中都有很多行,所以如果我可以在连接子句本身上过滤行,那就太好了。谢谢你的帮助 !

回答

4

您需要的两部分使用相同的匿名类型(具有相同的属性名称)的加入:

on new { t1.id, otherId = 2 } equals new { t2.id, t2.otherId } 

您的文字意味着你真的想加入一个单一值;如果是这样,你不需要一个匿名类型都:当你加入使用匿名类

on t1.id equals t2.otherid 
4

,这些类的名字的成员必须匹配。这个问题很容易被添加姓名您的匿名类的成员解决:

int id = 2; 

(from t1 in Table1 
join t2 in Table2 
on new { Id = t1.id, OtherId = id } 
    equals new { Id = t2.id, OtherId = t2.otherid } 
select t1).ToList(); 

虽然,我就越看它,我就越意识到加入并不需要是复杂的。它看起来像你正在加入静态ID。你应该能够逃脱它的where子句这将减少加入到一个值:

int id = 2; 

(from t1 in Table1 
from t2 in Table2 
on t1.id equals t2.id 
where t2.otherid = id 
select t1).ToList(); 
0

我看到了两个可能的解决方案:

这种变异预过滤器表2,然后执行联接。

 int id =2; 
    (from t1 in Table1 
    join t2 in (from a in Table2 where a.otherid == id select a) 
    on t1.id equals t2.id 
    select t1).ToList();

这是您的原始代码的调试版本。因为编译器在创建匿名对象时使用属性名称,所以必须明确名称。

 int id =2; 
    (from t1 in Table1 
    join t2 in Table2 
    on new { Id1 = t1.id, Id2 = id } equals new { Id1 = t2.id, Id2 = t2.otherid } 
    select t1).ToList();

心连心,马克