【问题标题】:using linq with Join and Max using DataTables使用 linq 与 Join 和 Max 使用 DataTables
【发布时间】:2017-05-26 12:53:39
【问题描述】:

请原谅我的 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 的最后一行,例如
ID 文本
1 '记录 1 的最终评论'
2 '记录 2 的最终评论'

使用 C# 我有两个数据表

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。

【问题讨论】:

    标签: c# linq join datatable max


    【解决方案1】:

    首先,请注意上帝给了我们 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()
                   }
    

    【讨论】:

    • 詹姆斯,非常感谢。 “Text = result.Last().select(l=>l.Text) 行无法编译。当我删除 .select(l=l.Text) 时,它会编译但不返回任何结果。
    猜你喜欢
    • 1970-01-01
    • 2014-09-16
    • 1970-01-01
    • 1970-01-01
    • 2021-07-08
    • 1970-01-01
    • 2021-10-18
    • 2010-10-06
    • 1970-01-01
    相关资源
    最近更新 更多