У меня есть список категорий:
╔════╦═════════════╦═════════════╗
║ 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, это означает, что это корневая категория.
Что такое самый приятный способ, чтобы преобразовать его в древовидную структуру, как показано ниже?
Другими словами - как переносить данные из этой структуры:
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),
};