C# - 从SQL到Linq - 左外连接/内连接

时间:2017-05-03 11:19:01

标签: c# sql linq left-join inner-join

我在SQL中得到了这个:

有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和Echo都有字符串a,b,c,d,e,f,g,h,i,j,k。

我试图转换为Linq,但我没有得到正确的连接语法。你能告诉我它应该怎么样吗? 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();
}

感谢您的帮助,也许这有点令人困惑。因为我改变了变量名。 抱歉英文不好btw

1 个答案:

答案 0 :(得分:3)

根据MSDN

  

要在LINQ中执行左外连接,请将DefaultIfEmpty方法与组连接结合使用,以指定在左侧元素没有匹配项时生成的默认右侧元素。您可以使用null作为任何引用类型的默认值,也可以指定用户定义的默认类型。

据我所知,您首先通过GroupJoin加入所有数据。这将根据关键相等性对两个序列的元素进行关联并对结果进行分组。&#34;然后,以下from指定默认的右侧元素(通过使用DefaultIfEmpty())来生成左侧元素没有匹配项。您需要对所有左连接执行此操作:

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();
    }