具有多个条件和子句的C#EF Linq语法查询
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了具有多个条件和子句的C#EF Linq语法查询相关的知识,希望对你有一定的参考价值。
我在实体框架上有一个带有查询语法的linq。这是sql
Select * from x
join y on y.a = x.a
join p on p.b = x.b and x.n in (3,4)
--other joins
这是linq
var k = from typeX in x
join typeY in y on y.a equals x.a
join typeP in p on p.b = x.b ???? (AND x.n in 3,4???)
//Other joins
这些都不起作用
join p in p on x.b equals p.b and x.n.Contains(3,4)
甚至或,||和&&不起作用,不被识别为关键字
也使用括号(带||或,和里面)不起作用。
我错过了什么?
我需要连接多个条件,其中一个是“IN CLAUSE”。
谢谢
答案
Here is a DotNetFiddle以我从你的问题中得到的一个工作实例:
您可以将3,4
放入数组并将其添加到LINQ查询中,然后检查数组是否包含x.n
:
int[] myNumbers = new int[] 3, 4;
join p in pData on x.b equals p.b where myNumbers.Contains(x.n)
这是完整的查询(变量与你的稍有不同,所以我更容易阅读它们,但应该是相同的逻辑):
int[] myN = new int[] 3, 4;
var result = from typeX in theX
join typeY in theY on typeX.a equals typeY.a
join typeP in theP on typeX.b equals typeP.b where myN.Contains(typeX.n)
join typeD in theD on typeX.z equals typeD.z
select typeX;
另一答案
我对LINQ的查询语法并不熟悉,因此我将展示如何使用Method语法来完成它。
您想要连接多个表,并且在一些连接之后,您希望与表P一起加入。但是您不希望将所有先前的连接结果与表P连接,您只想使用那些具有xn的先前连接结果等于3或4。
如果你丢弃所有以前的连接结果,x.N值既不是3,也不是4,那么无论如何将它们放在先前的连接结果中是没有用的:
var requiredNvalues = new int[] 3, 4;
var result = X
.Where(x => requiredNvalues.Contains(x.N) // keep only the required x elements
// Join the remaining elements of X with Y:
.Join(Y,
x => x.A, // from every x in X take the A
y => y.A, // from every y in Y take y.A
// ResultSelector: when they match make one new object containing matching X and Y
(x, y) => new X=x, Y=y)
// join with third table:
.Join(Z,
previousJoinResult => previousJoinResult.X.Id,
// from every item in previous join result take X.Id
z => z.xId, // from every z from Zcollection take Xid,
// ResultSelector: when they match make one new object containing matching X Y Z
(previousJoinResult, z) => new X = previousJoinResult.X, Y = previousJoinResult.Y, Z = z
... etc, other joins
继续以类似的方式加入,直到你想加入P:
.Join(P,
previousJoinResult => previousJoinResult.X.b,
// from every X from the previous join result take b
p => p.b // from every p take b
// resultSelector: select X Y Z ... P
(previousJoinResult, p) => new
X = previousJoinResult.X,
Y = previousJoinResult.Y,
Z = previousJoinResult.Z,
...
P = p;
);
你好简单!
以上是关于具有多个条件和子句的C#EF Linq语法查询的主要内容,如果未能解决你的问题,请参考以下文章
具有多个 where 子句的 Linq to Datatable