【问题标题】:How to select all columns in LINQ Datatable join?如何选择 LINQ Datatable 连接中的所有列?
【发布时间】:2017-04-20 04:50:16
【问题描述】:
var collection = from t1 in dt1.AsEnumerable()
                 join t2 in dt2.AsEnumerable()
                 on t1["id"] equals t2["id"]
                 select new { Name = t1["name"], Group = t2["group"] };

我想在 SQL Server 内部联接查询中选择两个表的所有列,例如联接。

此外 如何将两个表的整个结果转换为数据表?

【问题讨论】:

  • 你可以从select new {...}的2个表中列出你需要的所有属性

标签: c# linq


【解决方案1】:
var collection = from t1 in dt1.AsEnumerable()
             join t2 in dt2.AsEnumerable()
             on t1["id"] equals t2["id"]
             select new { T1 = t1, T2 = t2 };

那么……

编辑:

类似的东西

//clone dt1, copies all the columns to newTable 
DataTable newTable = dt1.Clone();

//copies all the columns from dt2 to newTable 
foreach(var c in dt2.Columns)
    newTable.Columns.Add(c);

//now newTable has all the columns from the original tables combined

//iterates over collection
foreach (var item in collection) {
    //creates newRow from newTable
    DataRow newRow = newTable.NewRow();
    //iterate the columns, gets values from either original table if column name is there
    foreach(var c in newTable.Columns)
        newRow[c.ColumnName] = item.T1.ContainsColumn(c.ColumnName) ?  item.T1[c.ColumnName] : item.T2[c.ColumnName];
    newTable.Rows.Add(newRow);
}

这会奏效。但如果 dt1 和 dt2 共享多个同名的列,则可能会丢失一些数据。

【讨论】:

  • 这就是我将能够逐行访问的方式。 :( 我想将结果转换为数据表。如何将两个表的整个结果转换为数据表?
  • 片段完成。我强烈建议您使用自动化程度较低的版本(从内部连接手动命名每一列)。正如我在答案中提到的,如果 dt1 和 dt2 有同名的列,它只会获取其中一个(dt1)的值,而不是另一个。
【解决方案2】:

虽然您无法将它们展开为列,但您可以简单地返回实体。例如:

select new { CTLJCRJOB, CTLRFDSTM }

如果您需要将其展平,则必须自己写出映射,但仍然非常简单。

引用自:

Select All columns for all tables in join + linq join

如果您想投影成扁平类型,您必须手动指定每个。您的另一个选择是让您的组合类型包含两个对象,并且这些对象自然会带来它们的属性。

select new 
{
    Object1 = object1,
    Object2 = output
};

您可以像 myObj.Object1.Property1、myObj.Object2.Property4 等一样使用它。

最后一个仍然涉及一些手动工作的选项是定义一个适当的类型,并使用一个构造函数或构建器方法来完成将您的对象属性分割成扁平类型的工作。您仍然执行手动映射,但将其与查询逻辑隔离开来。

select new CombinedType(object1, output);
//or 
select builder.GetCombinedType(object1, output);

引用自

Select all columns after JOIN in LINQ

【讨论】:

  • 您永远不应该发布仅链接的答案,因为如果粘贴在这里的 URL 已失效,它将是无效的。参考this
  • 感谢您指出我的错误,我从来不知道存在这样的协议。即使@DesertFox 已经给出了答案,我也会编辑我的答案。
【解决方案3】:
var collection = (from t1 in dt1.AsEnumerable()
                 join t2 in dt2.AsEnumerable()
                 on t1  ["id"] equals t2  ["id"]
                 select new { Name = t1  ["name"], Group = t2  ["group"] }).ToList() ;

希望这会有所帮助

【讨论】:

  • 我的表包含 62 列。我怎样才能一一指定这样的列?名称,组等
  • 如果您可以更好地使用 SP 或基本查询检索数据,然后将它们作为对象进行操作。我认为在 linq 查询中获取所有 62 列不是一个好主意
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多