Linq使用额外变量的多个联接条件 [英] Linq multiple join conditions using extra variables

查看:85
本文介绍了Linq使用额外变量的多个联接条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个查询:

SELECT *
FROM transaction t
JOIN transactionDetail toTrans ON t.id = toTrans.tId and toTrans.FlowDirection= 1
JOIN transactionDetail fromTrans ON t.id = fromTrans.tId and fromTrans.FlowDirection= 0

我曾尝试使用匿名类型重新创建,如

Which I tried to recreate using anonymous types, as explained here.

byte toFlow = 1;
byte fromFlow = 1;

from trans in data.Transactions
join toTrans in data.TransactionDetails on new {trans.id, toFlow} equals new {toTrans.tId, toTrans.FlowDirection}
join fromTrans in data.TransactionDetails on new { trans.id, fromFlow } equals new { fromTrans.tId, fromTrans.FlowDirection }

Flowdirection始终为1或0,因此我正在使用toFlow字节.但是,这会导致错误:

Flowdirection is always either 1 or 0, so I'm using the toFlow byte. This however, gives the error:

join子句中的表达式之一的类型不正确.

The type of one of the expressions in the join clause is incorrect.

根据

According to this answer, both name and types need to match. Which would mean:

byte FlowDirection= 1;

from trans in data.Transactions
join toTrans in data.TransactionDetails on new {trans.id, FlowDirection} equals new {toTrans.tId, toTrans.FlowDirection}
join fromTrans in data.TransactionDetails on new { trans.id, FlowDirection} equals new { fromTrans.tId, fromTrans.FlowDirection }

哪个有效!但是,第二个联接需要将FlowDirection的值设置为0而不是1.如何更改FlowDirection的值?我不能更改变量的名称,也不能在匿名对象内减去1,否则这将很容易.

Which works! However, the second join needs to have a FlowDirection of value 0 instead of 1. How can I change the value of FlowDirection? I can't change the name of the variable or subtract 1 inside the anonymous object, or else this would have been easy.

推荐答案

仅在评论中进行扩展:

您当然可以只使用两个常量(或文字)?

Surely you can just use two constants (or literals)?, i.e.

from trans in data.Transactions
join toTrans in data.TransactionDetails 
  on new {ID = trans.id, Flow = (byte)1} 
  equals new {Id = toTrans.tId, Flow = toTrans.FlowDirection}
join fromTrans in data.TransactionDetails 
  on new { Id = trans.id, Flow = (byte)0} 
  equals new { Id = fromTrans.tId, Flow = fromTrans.FlowDirection }

FlowDirect-1不能工作,因为它将FlowDirect变成了int吗?从一个字节中减去一个int可能会使该字节变成一个int吗?否则,我真的不知道为什么您的代码可以工作.

Could FlowDirect - 1 not work because it turns FlowDirect into an int instead? Does subtracting an int from a byte turn the byte into an int maybe? Otherwise, I really don't know why your code works.

是的,您需要将结果转换回字节(或将文字1转换为byte,以便使用字节运算符-")

Yes, you would need to cast the result back to byte (or the literal 1 to byte so that byte operator "-" is used)

这篇关于Linq使用额外变量的多个联接条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆