【问题标题】:Linq multiple join conditions using extra variablesLinq 使用额外变量的多个连接条件
【发布时间】:2015-03-06 13:13:27
【问题描述】:

我有这个问题:

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

我尝试使用匿名类型重新创建,如 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 字节。然而,这给出了错误:

join 子句中的其中一个表达式的类型不正确。

根据this的回答,名称和类型都需要匹配。这意味着:

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 }

哪个有效!但是,第二个连接需要有一个值为 0 而不是 1 的 FlowDirection。如何更改 FlowDirection 的值?我不能更改变量的名称或在匿名对象中减去 1,否则这很容易。

【问题讨论】:

  • 为什么不能只使用两个常量,或者只转换文字 (byte)0(byte)1
  • 谢谢斯图尔特,这对我有用!我现在有 {trans.id, FlowDirection = (byte)1}。我解决了这个问题。当我从字节中减去 1 时,它也变成了一个 int。见这里:stackoverflow.com/questions/941584/byte-byte-int-why

标签: c# linq


【解决方案1】:

另一个想法:

from trans in data.Transactions
join toTrans in data.TransactionDetails on trans.id equals new toTrans.tId
join fromTrans in data.TransactionDetails on trans.id equals fromTrans.tId
where toTrans.FlowDirection == 1 && fromTrans.FlowDirection == 1

我认为这个选项应该更容易阅读。

【讨论】:

    【解决方案2】:

    只是为了扩展评论:

    你当然可以只使用两个常量(或文字)吗?,即

    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 ?否则,我真的不知道为什么你的代码有效。

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

    【讨论】:

      【解决方案3】:

      如何更改 FlowDirection 的值?我无法更改变量的名称或在匿名对象中减去 1

      要更改匿名对象中的变量,只需执行以下操作:

      new { fromTrans.tId, FlowDirection = fromTrans.FlowDirection - 1 }
      

      例如。

      【讨论】:

      • 遗憾的是,这也是我尝试过的几种形式。我得到相同的类型错误。 FlowDirection -= 1 和 FlowDirect = toTrans.FlowDirection - 1 也不起作用。
      猜你喜欢
      • 1970-01-01
      • 2012-01-08
      • 1970-01-01
      • 2010-11-10
      • 2021-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-12
      相关资源
      最近更新 更多