C
C#2y ago
Alerin

How to generate a category tree

public class Category
{
public int Id { get; set; }

public Thread Thread { get; set; } = null!;
public Guid ThreadId { get; set; }

public string Name { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;

public ICollection<Category> Subcategories { get; set; } = new List<Category>();
public int? CategoryId { get; set; }
}
public class Category
{
public int Id { get; set; }

public Thread Thread { get; set; } = null!;
public Guid ThreadId { get; set; }

public string Name { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;

public ICollection<Category> Subcategories { get; set; } = new List<Category>();
public int? CategoryId { get; set; }
}
I have such categories, if we go down, i.e. Warzone2 -> DMZ -> Mission, then there is no problem. What if he wants to go up, with Mission ->DMZ -> Warzone2. How can I do it straight? The only thing that comes to my mind is foreach and each time checking if the element is generated correctly.
1 Reply
Alerin
Alerin2y ago
Or does anyone know how to google it?
public List<Models.Category> Parents { get; set; } = new();

public async Task GetParent(int id)
{
var p = await _context.Categories.SingleOrDefaultAsync(x => x.Id == id);
if (p != null)
{
Parents.Add(p);
if (p.CategoryId is not null)
await GetParent(p.CategoryId ?? 0);
}
}
public List<Models.Category> Parents { get; set; } = new();

public async Task GetParent(int id)
{
var p = await _context.Categories.SingleOrDefaultAsync(x => x.Id == id);
if (p != null)
{
Parents.Add(p);
if (p.CategoryId is not null)
await GetParent(p.CategoryId ?? 0);
}
}
Work