我有类别列表:
╔════╦═════════════╦═════════════╗
║ Id ║ Name ║ Parent_id ║
╠════╬═════════════╬═════════════╣
║ 1 ║ Sports ║ 0 ║
║ 2 ║ Balls ║ 1 ║
║ 3 ║ Shoes ║ 1 ║
║ 4 ║ Electronics ║ 0 ║
║ 5 ║ Cameras ║ 4 ║
║ 6 ║ Lenses ║ 5 ║
║ 7 ║ Tripod ║ 5 ║
║ 8 ║ Computers ║ 4 ║
║ 9 ║ Laptops ║ 8 ║
║ 10 ║ Empty ║ 0 ║
║ -1 ║ Broken ║ 999 ║
╚════╩═════════════╩═════════════╝
每个类别都有一个父级。当 parent 为 0 - 这意味着它是根类别。
将其转换为如下树结构的最佳方法是什么?
Sport
├ Balls
└ Shoes
Electronics
├ Cameras
│ ├ Lenses
│ └ Tripod
│
└ Computers
└ Laptops
Empty
换句话说 - 如何从这个结构中获取数据:
class category
{
public int Id;
public int ParentId;
public string Name;
}
进入这个:
class category
{
public int Id;
public int ParentId;
public string Name;
public List<Category> Subcategories;
}
以普遍的方式?// 通用意味着不仅适用于提到的类。
你有一些聪明的想法吗?;)
数据:
var categories = new List<category>() {
new category(1, "Sport", 0),
new category(2, "Balls", 1),
new category(3, "Shoes", 1),
new category(4, "Electronics", 0),
new category(5, "Cameras", 4),
new category(6, "Lenses", 5),
new category(7, "Tripod", 5),
new category(8, "Computers", 4),
new category(9, "Laptops", 8),
new category(10, "Empty", 0),
new category(-1, "Broken", 999),
};