【问题标题】:Linq return all columns from all tables in the joinLinq 返回连接中所有表的所有列
【发布时间】:2010-10-15 07:34:16
【问题描述】:

假设我有 2 个表,它们都包含动态列,我希望在执行左外连接后检索包含两个表中所有列的数据行集合(稍后我会将其绑定到网格视图)。

示例查询:

var query = from TableA in ds.Tables[0].AsEnumerable()
            join TableB in ds.Tables[1].AsEnumerable() on new { col1 = TableA.Field<Int32>("colA"), col2 = TableA.Field<DateTime>("colB") }
            equals new { col1 = TableB.Field<Int32>("colA"), col2 = TableB.Field<DateTime>("colB") }
            into GJ
            from sub in GJ.DefaultIfEmpty()
            select TableA;

问题: 我想同时选择 tableA 和 tableB。上面的示例查询有效,它在左外连接后填充 tableA 的所有列。但我希望从两个表中检索所有列。请指教。

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    只需将这两个部分都选择为匿名类型:

    var query = from TableA in ds.Tables[0].AsEnumerable()
                join TableB in [ ...] on [...] equals [...] into GJ
                from sub in GJ.DefaultIfEmpty()
                select new { RowA = TableA, RowB = sub };
    

    结果的每个元素将有两个属性:RowA 是来自 TableA 的一行,RowB 是来自 TableB 的匹配行 如果没有来自 @ 的行,则为 null 987654326@ 匹配 RowA

    【讨论】:

    • 感谢您的回答。假设这些是表 A 的列(列 A、列 B、列 C)和表 B 的列(列 A、列 B、列 D、列 E)。所以我希望提取一个包含所有列(ColumnA、ColumnB、ColumnC、ColumnD、ColumnE)的数据行集合。输出非常类似于 select * from tableA left outer join Tableb on [..some join..] ...你能详细说明我如何实现它吗?
    • @Alex:你可以在 select 子句中将它们展平......但为什么不把这两行分开?
    • 我的原因:有很多查询我要添加连接(以前没有),很多 AutoMapper 地图,而且时间不多:(。
    猜你喜欢
    • 2014-11-05
    • 1970-01-01
    • 2018-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-26
    • 2018-02-28
    • 1970-01-01
    相关资源
    最近更新 更多