[英]C# - from SQL to Linq - Left Outer Join/Inner Join
I got this in SQL: 我在SQL中得到了这个:
with 3 Values: value1, value2, value3 具有3个值:value1,value2,value3
SELECT A.a, A.b, E.c, B.d, A.e, A.f, A.g, D.h, D.i
FROM Alpha as A
INNER JOIN Beta as B ON A.b = B.k
LEFT OUTER JOIN Charlie as C ON C.a = A.a
LEFT OUTER JOIN Delta as D ON D.k = B.j
INNER JOIN Echo as E ON A.a = E.a
WHERE A.a = @value1 AND E.c = @value2 AND (A.a = @value3 OR @value3 = '') AND A.b = E.b
Alpha, Beta, Charlie, Delta and Echo have string a,b,c,d,e,f,g,h,i,j,k. Alpha,Beta,Charlie,Delta和Echo具有字符串a,b,c,d,e,f,g,h,i,j,k。
I've tried to convert into Linq, but I don't get the Syntax of join right. 我曾尝试将其转换为Linq,但没有获得正确的Join语法。 Can you show me how it should look?
您能告诉我它的外观吗? x)
X)
public static List<value> GetSmthn(string value1, string value2, string value3)
{
return (
from A in Alpha
join B in Beta on A.b equals B.k
join C in Charlie on A.a equals C.a
join D in Delta on B.j equals D.k
join E in Echo on E.a equals A.a
where (A.a == value1 && E.c == value2 && (A.a == value3 || value3 == "") && A.b == E.b)
select new value() { a = A.a, b = A.b, c = E.c, d = A.d, e = A.e, f = A.f, g = A.g, h = D.h i = D.i }
).ToList();
}
Thanks for help, maybe it's a bit confusing. 感谢您的帮助,也许有点令人困惑。 Cause I changed the variable-names.
原因我更改了变量名。 Sorry for the bad english btw
对不起,英语不好
To perform a left outer join in LINQ, use the DefaultIfEmpty method in combination with a group join to specify a default right-side element to produce if a left-side element has no matches.
要在LINQ中执行左外部联接,请结合使用DefaultIfEmpty方法和组联接来指定默认的右侧元素,如果左侧元素不匹配则生成该默认右侧元素。 You can use null as the default value for any reference type, or you can specify a user-defined default type.
您可以将null用作任何引用类型的默认值,也可以指定用户定义的默认类型。
From what I can tell, you first join all the data via a GroupJoin This "correlates the elements of two sequences based on key equality and groups the results." 据我所知,您首先通过GroupJoin连接所有数据,这“基于键相等性对两个序列的元素进行关联并将结果分组”。 Then, the following
from
specifies a default right-side element (by using DefaultIfEmpty()
) to produce if a left-side element has no matches. 然后,以下命令
from
指定默认的右侧元素(通过使用DefaultIfEmpty()
),以在左侧元素不匹配时生成。 You will need to perform this for all of your left joins: 您将需要对所有左联接执行此操作:
public static List<value> GetSmthn(string value1, string value2, string value3)
{
return (
from A in Alpha
join B in Beta on A.b equals B.k
join C in Charlie on A.a equals C.a into cgroup
from C in cgroup.DefaultIfEmpty()
join D in Delta on B.j equals D.k into dgroup
from D in dgroup.DefaultIfEmpty()
join E in Echo on E.a equals A.a
where (A.a == value1 && E.c == value2 && (A.a == value3 || value3 == "") && A.b == E.b)
select new value() { a = A.a, b = A.b, c = E.c, d = A.d, e = A.e, f = A.f, g = A.g, h = D.h i = D.i }
).ToList();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.