这是一个关于如何使用 LINQ 执行此操作的示例。首先是一个示例数据表。我假设顶级项目的父 ID 为 0。
var dataTable = new DataTable();
dataTable.Columns.Add("Id", typeof(Int32));
dataTable.Columns.Add("ParentId", typeof(Int32));
dataTable.Columns.Add("Name", typeof(String));
dataTable.Rows.Add(new Object[] { 1, 0, "A" });
dataTable.Rows.Add(new Object[] { 2, 1, "B" });
dataTable.Rows.Add(new Object[] { 3, 1, "C" });
dataTable.Rows.Add(new Object[] { 4, 0, "D" });
dataTable.Rows.Add(new Object[] { 5, 4, "E" });
表示每项数据的类:
class Item {
public Int32 Id { get; set; }
public String Name { get; set; }
public IEnumerable<Item> Children { get; set; }
}
获取特定项的子项的函数:
IEnumerable<DataRow> GetChildren(DataTable dataTable, Int32 parentId) {
return dataTable
.Rows
.Cast<DataRow>()
.Where(row => row.Field<Int32>("ParentId") == parentId);
}
创建包含子集合的项目的函数。此函数将向下递归层次结构:
Item CreateItem(DataTable dataTable, DataRow row) {
var id = row.Field<Int32>("Id");
var name = row.Field<String>("Name");
var children = GetChildren(dataTable, id)
.Select(r => CreateItem(dataTable, r))
.ToList();
return new Item { Id = id, Name = name, Children = children };
}
获取顶级项目行的函数:
IEnumerable<DataRow> GetTopLevelRows(DataTable dataTable) {
return dataTable
.Rows
.Cast<DataRow>()
.Where(row => row.Field<Int32>("ParentId") == 0);
}
把它们放在一起:
var items = GetTopLevelRows(dataTable)
.Select(row => CreateItem(dataTable, row))
.ToList();