使用 Linq 加入动态数据表
我有两个数据表,其列是动态的,并且它们都有一个公共列。 现在我想加入这两个表。 以获得合并结果。
提前致谢。
I have two data tables whose columns are dynamic and they both have one common column.
Now I want to join these two tables.
To get combined result.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您好,您可能希望连接运行时生成的两个数据表。查看此链接。可能对您有用
从两个数据表中查找公共列并将其用于 LINQ 中的联接条件
Hi you might be looking to join the two data tables which are generated on runtime. Check out this link. Might be useful for you
Finding common columns from two datatable and using those for Join condition in LINQ
一种简单的方法是在表上使用 AsEnumerable() 并将它们连接到公共列数据上。
假设您的表格如下所示:
[Table1] -> [ID] [名称] [位置] | [表2]-> [ID] [Description]
和 ID 列具有相同的值然后您只需连接 ID 列上的表并选择结果数据集
结果数据:
A simple way is to use AsEnumerable() on the tables and to join them on the common column data.
Let's assume that your tables look like this:
[Table1] -> [ID] [Name] [Location] | [Table2] -> [ID] [Description]
and the ID column has the same valuesThen you just have to join the tables on the ID columns and select the resulting data set
The resulting data:
这并不那么容易,如果不使用
ExpandoObject
则更是如此,因为 LINQ 通常经过调整以生成强类型对象,您需要在编译时了解这些对象的架构。我看到这种情况发生的一种方式是通过组合通过转换调用的方法,其中该方法将生成一个动态对象,其中包含所有发现的字段的组合select in linq 并不完全像 SQL select,它只是提供了一个用于转换的占位符,很简单、复杂甚至外部调用代码。
注意:如果您不想使用动态,则可以通过首先枚举两个表中的所有列并创建第三个表来类似地制定解决方案。然后,CombineMe 更改为生成
DataRow
而不是ExpandoObject
,并且最终枚举 p,并将其所有条目(DataRow
的组合实例)添加到结果表。It's not that easy, more so without using
ExpandoObject
because LINQ is generally tuned to produce strongly typed objects for which you need to know the schema at compile time. A way I see this happening is through combining method being invoked via transformation, where the method will generate a dynamic object with a combination of all discovered fieldsselect in linq is not exactly like SQL select, it just provides a placeholder for transformation be it simple, complex or even external calling code.
NOTE: If you do not want to use dynamic then a solution can be similarly made by first enumerating all columns in both tables and creating a third table. CombineMe is then changed to generate
DataRow
instead ofExpandoObject
and p is finally enumerated and all its entries (combined instances ofDataRow
) are added to the resulting table.