C# 如何对DataTable中的分层数据进行自引用选择?
我有一个DataTable,比如说,有两列:ReportId和ParentReportId。我想选择其父级尚未在DataTable中列出的所有报告。我想从SQL语法中做一些类似的事情,但我知道这不起作用:C# 如何对DataTable中的分层数据进行自引用选择?,c#,.net,ado.net,datatable,C#,.net,Ado.net,Datatable,我有一个DataTable,比如说,有两列:ReportId和ParentReportId。我想选择其父级尚未在DataTable中列出的所有报告。我想从SQL语法中做一些类似的事情,但我知道这不起作用: DataRow[] foo = drParentRow = dt.Select("ParentReportId NOT IN(ReportId)"); 在这种情况下,如何从该数据集中获取这些记录?我认为您必须为此使用一些LINQ: var noParents = dt.AsEnumerabl
DataRow[] foo = drParentRow = dt.Select("ParentReportId NOT IN(ReportId)");
在这种情况下,如何从该数据集中获取这些记录?我认为您必须为此使用一些LINQ:
var noParents = dt.AsEnumerable().Where(x => x["ReportParentID"] != DBNull.Value &&
!dt.rows.Any(y => y["ReportID"] == x["ReportParentID"]);
var reportIds = dt.AsEnumerable().Select(row => row.Field<int>("ReportId"));
var foo = from row in dt.AsEnumerable()
let parentReportId = row.Field<int>("ParentReportId")
where !reportIds.Contains(parentReportId)
select row;
dt.Rows没有.Where方法。我正在使用System.Data和System.Linq。几分钟前我更新了答案,您必须执行dt.AsEnumerable。注意:我一直想知道为什么C语言的用户在数据表的Linq查询中明确地编写AsEnumerable,因为我不是被迫在VB中这样做的。现在我知道这是VB.NET的几个优点之一。通常VB更详细: