-1

I have a c# list with no limits of levels with parentID´s. How do I organize the list, so the output would look like:

root1
----sub1
--------sub3
------------sub4
root2
----sub2

My list:

var categories = new List<categoryModel>();
categories.Add(new categoryModel { ID = 1, Name = "root 1", ParentID = 0 });
categories.Add(new categoryModel { ID = 2, Name = "root 2", ParentID = 0 });
categories.Add(new categoryModel { ID = 3, Name = "sub 1", ParentID = 1 });
categories.Add(new categoryModel { ID = 4, Name = "sub 2", ParentID = 2 });
categories.Add(new categoryModel { ID = 5, Name = "sub 4", ParentID = 6 });
categories.Add(new categoryModel { ID = 6, Name = "sub 3", ParentID = 3 });

public class categoryModel
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int ParentID { get; set; }
}
bongii
  • 1
  • 1
  • 2
    Use a tree structure for that – Pavel Anikhouski Dec 24 '19 at 14:16
  • 1
    You could find more about tree structure here: https://stackoverflow.com/questions/66893/tree-data-structure-in-c-sharp – dino Dec 24 '19 at 14:22
  • Convention-based data structures like this are rarely a good idea. There are other data structures besides lists that would better accomplish what you're attempting. Without seeing exactly what you're doing, I cannot recommend one, but as Pavel has mentioned, it looks like the job for a tree of some type. – Captain Skyhawk Dec 24 '19 at 14:22

2 Answers2

0

As suggested in the comments, a tree structure is what you are looking for.

public class Node{
    public string Value;
    public List<Node> Descendants;

    public Node(string value) { Value = value; }
    public void Add(Node n) { Descendants.Add(n); }
}

var root = new Node("root");
var n1 = new Node("sub")
root.Add(n1);

You can have a generic tree declaring Node<T>

Alvin Sartor
  • 2,249
  • 4
  • 20
  • 36
0

They are right, u should adopt a tree structure. To fit your structure to a tree structure just need some fixes to your model

public class Category
{
   public Category()
  {
    SubCategories = new HashSet<Category>();
  }

    public int ID { get; set; }
    public string Name { get; set; }
    public int? ParentID { get; set; }
    [Foreignkey ("ParentId")]
    public Category Parent {get; set;}
    public ICollection<Category> SubCategories { get; set; }
}

Then you can start querying where parentid is null then navigate to SubCategories.

Frederic
  • 1,018
  • 6
  • 11