如何正确重写这个 linq 查询?
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();
目前,上面的查询给了我一个编译错误:
连接表达式之一的类型不正确。
正如您在上面的查询中看到的,我想像在 sql 中一样加入单个整数值。我想要这些,以便查询更快,并且我不想在最后执行 where ,因为这意味着它将获取所有行,然后使用 where 子句进行过滤。由于两个表中都有很多行,如果我可以过滤 join 子句本身的行,那就太好了。感谢您的帮助 !
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();
Currently the above query gives me a compilation error saying
The type on one of the join expressions is incorrect.
As you can see in the above query I want to join on a single integer value as you would in sql. I want to these so that query is faster and I don't want to do a where at the end because that would mean it will get all the rows and then filter with the where clause. As I have lot of rows in both the tables it would be good if I can filter rows on join clause itself. Thanks for your help !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
发布评论
评论(3)
当您使用匿名类加入时,这些类的成员名称必须匹配。通过向匿名类的成员添加名称可以轻松解决该问题:
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();
我看到两种可能的解决方案:
此变体预过滤 Table2,然后执行联接。
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();
HTH,马克
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
您需要在连接的两半中使用相同的匿名类型(具有相同的属性名称):
您的文本暗示您实际上想要连接单个值;如果是这样,您根本不需要匿名类型:
You need to use the same anonymous type (with the same property names) in both halves of the join:
Your text implies that you actually want to join on a single value; if so, you don't need an anonymous type at all: