请原谅我的Newby尝试,但我花了一个星期来解决这个愚蠢的问题,并决定使用LINQ
这是我的SQL查询 - 使用SQL查询构建器生成
SELECT TABLE1.ID, MAX(DISTINCT TABLE2.TEXT) AS Expr1
FROM TABLE1
INNER JOIN TABLE2 ON TABLE1.ID = TABLE2.PARENT_ID
GROUP BY TABLE1.ID
我想显示Table1行和最后一个table2行例如
身份证明文字
1'记录1'的最终评论
2'记录2'的最终评论
使用C#我有两个DataTables
DataTable DT_Nodes = sess_nodes.ds.Tables["TABLE1"];
DataTable DT_Sticky = sess_nodes.ds.Tables["TABLE2"];
var linq_test = from tab1 in DT_Nodes.AsEnumerable()
join tab2 in DT_Sticky.AsEnumerable()
on tab1["ID"] equals tab2["PARENT_ID"]
group tab1 by tab1.Field<long>("ID") into result
select <I am stuck here>;
我想使用循环
显示结果foreach(DataRow resultrow in linq_test)
{
<stuck here also>
long id = resultrow.table1["ID"]; // This needs to be the ID in table1
long id_tab2 = resultrow.table2["ID"] // This needs to be the last if the ID's of table2
}
我尝试了各种方法,但linq语法已经打败了我,网上的大多数样本都没有使用DataTables。
答案 0 :(得分:1)
首先,请注意,Good Lord给了我们LINQ,所以我们可以停止使用DataTables ....
DataTable DT_Nodes = sess_nodes.ds.Tables["TABLE1"];
DataTable DT_Sticky = sess_nodes.ds.Tables["TABLE2"];
var linq_test = from tab1 in DT_Nodes.AsEnumerable()
join tab2 in DT_Sticky.AsEnumerable()
on tab1["ID"] equals tab2["PARENT_ID"]
group new {Table1=tab1, Text=tab2["TEXT"]}
by tab1.Field<long>("ID") into result
select new {
Id = result.Key,
Text = result.Last().Text
};
如果Table1中我们唯一需要的是ID,那么我们可以简化一下:
var linq_test = from tab1 in DT_Nodes.AsEnumerable()
join tab2 in DT_Sticky.AsEnumerable()
on tab1["ID"] equals tab2["PARENT_ID"]
group tab2["TEXT"] by tab1.Field<long>("ID") into result
select new {
Id = result.Key,
Text = result.Last()
}