C#Linq组合了两个DataTables的数据 [英] C# Linq combine data from two DataTables
问题描述
我有两个DataTable,其中一个字段连接两个表。我想加入这两个表,并将每个DataTable中的一些(或全部)列添加到一个新列中。我不认为使用LINQ会很困难,但我不知所措。
在SQL中它很容易,我只想写
I have two DataTables with one field connecting the two tables. I want to join the two tables and get some (or all) of the columns from each DataTable into a new one. I wouldn't think this would be difficult using LINQ but I am at a loss.
In SQL it is easy, I would just write
SELECT Table1.ID, Table1.Field1, Table2.Field2
FROM Table1 INNER JOIN Table2 ON Table1.ID = Table12.ID
什么是LINQ相当于上面的SQL代码??
我发现的所有例子都是这样的:
What is the LINQ equivalent to the SQL code above??
All the examples I find look something like this:
var query =
from tbl1 in Table1.AsEnumerable()
join tbl2 in Table2.AsEnumerable() on tbl1["ID"] equals tbl2["ID"]
select new { ID = tbl1["ID"], Field1 = tbl1["Field1"], Field2 = tbl2"Field2"]};
DataTable newTable = new DataTable();
newTable.Columns.Add("ID",typeof(Guid));
newTable.Columns.Add("Field1", typeof(string));
newTable.Columns.Add("Field2",typeof(string));
foreach (var rowInfo in query)
{
newTable.Rows.Add(rowInfo.ID, rowInfo.Field1, rowInfo.Field2);
}
这是一个很好的解决方案,如果他们真的是小桌子,但我'我正在使用具有10个左右列的表,这看起来非常混乱。是不是像SQL一样更直截了当?
That is a fine solution if they are really small tables but I'm working with tables that have 10 or so columns and that would look really messy. Is there not a more straight-forward way like in SQL?
推荐答案
创建数据表毫无意义。按照您的方式访问字段是没有意义的。你没有数据模型,所以你可以做tbl2.Id吗?为什么使用EF然后将结果填入数据表?
您可以使用反射来执行此操作。但你为什么要这样?如果您通常要创建连接,则应定义一个包含结果的类,然后选择一个列表。我可能更进一步,在一个过程中执行请求,让它返回一个强类型的类,并完成它。
Creating a data table at all makes no sense. Accessing fields the way you are, makes no sense. Do you not have a data model so you can just do tbl2.Id ? Why use EF then stuff the result in to a data table ?
You can probably use reflection to do this. But why would you ? If you're creating a join commonly, you should define a class to contain the results, and select a list of those. I'd probably go one step further and do the request in a procedure, and have it return a strongly typed class, and be done with it.
这篇关于C#Linq组合了两个DataTables的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!