如何在DataTable中对层次数据进行自引用选择?

时间:2011-10-27 21:20:31

标签: c# .net ado.net datatable

我有一个DataTable,比方说有两列:ReportId和ParentReportId。我想选择其父级尚未在DataTable中列出的所有报告。我想做这样的事情(取自SQL语法),但我知道这不起作用:

DataRow[] foo = drParentRow = dt.Select("ParentReportId NOT IN(ReportId)");

在这种情况下,如何从此数据集中获取这些记录?

2 个答案:

答案 0 :(得分:0)

var noParents = dt.AsEnumerable().Where(x => x["ReportParentID"] != DBNull.Value && 
                                      !dt.rows.Any(y => y["ReportID"] == x["ReportParentID"]);

答案 1 :(得分:0)

我认为你将不得不为此使用一些LINQ:

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;