【问题标题】:Linq left outer joinLinq 左外连接
【发布时间】:2011-08-10 02:06:18
【问题描述】:

我最终需要的是通用函数,它需要两个数据表和 2 个表键并返回 Joined 数据表。所以这是我解决它的第一步。

如何在VB中编写以下T-SQL示例的Linq示例?

SELECT * FROM
Table1
LEFT OUTER JOIN
Table2
ON Table1.key = Table2.key

【问题讨论】:

    标签: vb.net linq join database-table


    【解决方案1】:

    应该是这样的:

    Dim JoinedResult = From t1 In Table1 
        Group Join t2 In Table2 
           On t1.key Equals t2.key 
           Into RightTableResults = Group 
        From t2 In RightTableResults.DefaultIfEmpty 
        Select t1.Prop1, 
           t2.Prop2        
    

    我不是 VB 人(不再),但我认为这可行。

    【讨论】:

    • 感谢您的回答。我在这里有点困惑。 Prop1 和 Prop2 是什么?它们是列吗?我遇到的问题是我无法选择列,因为我正在尝试编写通用函数。
    • Prop1Prop2 只是表格中的示例列。再次阅读您的问题,我可以看到您想要一个通用功能。我会想办法的。
    【解决方案2】:

    您可以简单地使用现有的 Join 方法

    public static IEnumerable<TResult> Join<TOuter, TInner, TKey, TResult>(
        this IEnumerable<TOuter> outer,
        IEnumerable<TInner> inner,
        Func<TOuter, TKey> outerKeySelector,
        Func<TInner, TKey> innerKeySelector,
        Func<TOuter, TInner, TResult> resultSelector
    )
    

    例如:

    table1.Join(table2, t1 => t1.Key, t2 => t2.Key, (t1, t2) => new { Table1 = t1, Table2 = t2 });
    

    可以找到更多的重载和例子http://msdn.microsoft.com/en-us/library/system.linq.enumerable.join.aspx

    请原谅我的 c# 示例

    【讨论】:

    • 这不是左外连接顺便说一句
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-27
    • 2011-08-04
    • 2011-03-25
    相关资源
    最近更新 更多