Recursive TreeView in ASP.NET - c#

I have an object of type list from which I wish to use to populate a treeview in asp.net c#.
Each object item has:
id | Name | ParentId
so for example:
id | Name | ParentId
-------------------------
1 | Alice | 0
2 | Bob | 1
3 | Charlie | 1
4 | David | 2
In the above example, the parent would be Alice having two children Bob and Charlie. David is the child of Bob.
I have had many problems trying to dynamically populate the treeview recursively in c# ASP.NET
Does any one have a simple solution?
Btw: you can use People.Id, People.Name and People.ParentId to access the members since it is an object belonging to list.
I can post you my code so far (many attempts made) but not sure how useful it will be.

I think this should get you started. I created a MyObject class to mimic your object .
public class MyObject
{
public int Id;
public int ParentId;
public string Name;
}
Here is a method to recursivley add tree view nodes based on the list.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<MyObject> list = new List<MyObject>();
list.Add(new MyObject(){Id=1, Name="Alice", ParentId=0});
list.Add(new MyObject(){Id=2, Name="Bob", ParentId=1});
list.Add(new MyObject(){Id=3, Name="Charlie", ParentId=1});
list.Add(new MyObject(){Id=4, Name="David", ParentId=2});
BindTree(list, null);
}
}
private void BindTree(IEnumerable<MyObject> list, TreeNode parentNode)
{
var nodes = list.Where(x => parentNode == null ? x.ParentId == 0 : x.ParentId == int.Parse(parentNode.Value));
foreach (var node in nodes)
{
TreeNode newNode = new TreeNode(node.Name, node.Id.ToString());
if (parentNode == null)
{
treeView1.Nodes.Add(newNode);
}
else
{
parentNode.ChildNodes.Add(newNode);
}
BindTree(list, newNode);
}
}

This is a sample with Category entity that references itself. First we should prepare our data source:
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public int? ParentId { get; set; }
public virtual Category Parent { get; set; }
public virtual ICollection<Category> Children { get; set; }
public byte[] Image { get; set; }
}
public class Product
{
public int Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public Category ProductCategory { get; set; }
public int ProductCategoryId { get; set; }
public byte[] Image { get; set; }
}
public List<Category> GethierarchicalTree(int? parentId=null)
{
var allCats = new BaseRepository<Category>().GetAll();
return allCats.Where(c => c.ParentId == parentId)
.Select(c => new Category()
{
Id = c.Id,
Name = c.Name,
ParentId = c.ParentId,
Children = GetChildren(allCats.ToList(), c.Id)
})
.ToList();
}
public List<Category> GetChildren(List<Category> cats, int parentId)
{
return cats.Where(c => c.ParentId == parentId)
.Select(c => new Category
{
Id = c.Id,
Name = c.Name,
ParentId = c.ParentId,
Children = GetChildren(cats, c.Id)
})
.ToList();
}
Then in our code behind we have:
protected void Page_Load(object sender, EventArgs e)
{
var hierarchicalData = new CategoryRepository().GethierarchicalTree();
tv1.Nodes.Clear();
var root = new TreeNode("0","Root");
tv1.Nodes.Add(root);
BindTreeRecursive(hierarchicalData, root);
}
private void BindTreeRecursive(List<Category> hierarchicalData, TreeNode node)
{
foreach (Category category in hierarchicalData)
{
if (category.Children.Any())
{
var n = new TreeNode(category.Name, category.Id.ToString());
node.ChildNodes.Add(n);
BindTreeRecursive(category.Children.ToList(), n);
}
else
{
var n = new TreeNode(category.Name, category.Id.ToString());
node.ChildNodes.Add(n);
if (new ProductRepository().Get(a => a.ProductCategoryId == category.Id).Any())
{
var catRelatedProducts = new ProductRepository().Get(a => a.ProductCategoryId == category.Id).ToList();
foreach (Product product in catRelatedProducts)
{
n.ChildNodes.Add(new TreeNode(product.Name,product.Id.ToString()));
}
}
}
}
}

//In load for example
if (!IsPostBack)
{
DataSet ds = new DataSet();
ds = getRoles(); //function that gets data collection from db.
tvRoles.Nodes.Clear();
BindTree(ds, null);
tvRoles.DataBind();
}
private void BindTree(DataSet ds, TreeNode parentNode)
{
DataRow[] ChildRows;
if (parentNode == null)
{
string strExpr = "ParentId=0";
ChildRows = ds.Tables[0].Select(strExpr);
}
else
{
string strExpr = "ParentId=" + parentNode.Value.ToString();
ChildRows = ds.Tables[0].Select(strExpr);
}
foreach (DataRow dr in ChildRows)
{
TreeNode newNode = new TreeNode(dr["Name"].ToString(), dr["Id"].ToString());
if (parentNode == null)
{
tvRoles.Nodes.Add(newNode);
}
else
{
parentNode.ChildNodes.Add(newNode);
}
BindTree(ds, newNode);
}
}

Related

C# Recursively loop over object and return all children [duplicate]

This question already has answers here:
How to flatten tree via LINQ?
(15 answers)
Closed 6 months ago.
I've the following class, which contains some info about the object it also has a list of same object and hierarchy goes on. This is my class:
public class Category
{
public List<Category>? children { get; set; }
public bool var { get; set; }
public string? name { get; set; }
public bool leaf { get; set; }
public int category_id { get; set; }
}
I have a list List<Category> categories; I want to loop over the list and go deep down in every children and create this new object:
public class DBCategory
{
public string? CategoryId { get; set; }
public string? CategoryName { get; set; }
public string? CategoryParentId { get; set; }
}
I have tried to loop over my list and then call function recursively but I'm also stuck there because children isn't a category class but a list of categories so the function fails to accept parameter in if clause:
foreach (var category in categories)
{
CreateDBCategory(category);
}
DBCategory CreateDBCategory(Category category)
{
DBCategory dBCategory = new DBCategory();
if (category.children.Count > 0)
{
return CreateDBCategory(category.children);
}
return dBCategory;
}
I have also tried to reach most bottom child by this, but this code says not all paths return a value.
DBCategory testFunction(List<Category> categories)
{
foreach (var category in categories)
{
if (category.children.Count > 0)
{
return testFunction(category.children);
}
else
{
return category;
}
}
}
One of the common ways to handle such cases is to have the List to be filled passed as an argument to the method. E.g.:
List<DBCategory> dbCategories = new();
foreach (var category in categories)
{
CreateDBCategory(category, dbCategories);
}
void CreateDBCategory(Category category, List<DBCategory> dbCategories)
{
DBCategory dbCategory = new DBCategory();
// Fill dbCategory
dBCategories.Add(dbCategory);
if (category.children != null)
{
// recurse over all children categories and add them to the list
foreach (var child in category.children)
{
CreateDBCategory(child, dbCategories);
}
}
}
It could be argued that this solution does not fit the functional paradigm as it has side effects (modifying the passed in List), so an alternative, more functional approach would be to return a list from the recursive method, e.g.:
List<DBCategory> dbCategories = new();
foreach (var category in categories)
{
dbCategories.AddRange(CreateDBCategory(category));
}
IEnumerable<DBCategory> CreateDBCategory(Category category)
{
List<DBCategory> dbCategories = new();
DBCategory dbCategory = new DBCategory();
// Fill dbCategory
dbCategories.Add(dbCategory);
if (category.children != null)
{
// recurse over all children categories and add them to the list
foreach (var child in category.children)
{
dbCategories.AddRange(CreateDBCategory(child));
}
}
return dbCategories;
}
This does however perform a lot more allocations, so in some cases it can perform slower than the first approach
Noted that this is untested, but it should work.
IEnumerable<DBCategory> FlattenCategories(IEnumerable<Category> categories, int parentId)
{
DBCategory selector(Category cat, int pid) =>
return categories
.Select(c => new DBCategory {
CategoryId = cat.category_id,
CategoryName = cat.name,
CategoryParentId = pid,
})
.Concat(categories.SelectMany(
c => FlattenCategories(c.children, c.category_id)
);
}
Just call FlattenCategories(categories).ToList(); to get List<DBCategory>
From here, A generic solution.
public static IEnumerable<T> Traverse<T>(
this T root,
Func<T, IEnumerable<T>> childrenSelector)
{
ArgumentNullException.ThrowIfNull(childrenSelector);
var stack = new Stack<T>();
stack.Push(root);
while(stack.Count > 0)
{
var current = stack.Pop();
yield return current;
foreach(var child in childrenSelector(current))
{
stack.Push(child);
}
}
}
So you can do this,
foreach(var category in root.Traverse(c => c.Children))
{
...
}
or some LINQ. The beauty is, it won't allocate more memory than your biggest leaf collection and won't have a stack overflow for deep trees.
Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication40
{
class Program
{
static void Main(string[] args)
{
Category root = new Category()
{
children = new List<Category>() {
new Category() {
children = new List<Category>() {
new Category() {
var = true,
name = "2A",
leaf = true,
category_id = 21
},
new Category() {
var = true,
name = "2B",
leaf = true,
category_id = 22
}
},
var = true,
name = "1A",
leaf = false,
category_id = 1
},
new Category() {
children = new List<Category>() {
new Category() {
var = true,
name = "2C",
leaf = true,
category_id = 23
},
new Category() {
var = true,
name = "2D",
leaf = true,
category_id = 24
}
},
var = true,
name = "1B",
leaf = false,
category_id = 2
},
},
category_id = 0,
name = "root",
leaf = false,
var = true
};
List<DBCategory> children = DBCategory.GetChildren(root,null);
}
}
public class Category
{
public List<Category> children { get; set; }
public bool var { get; set; }
public string name { get; set; }
public bool leaf { get; set; }
public int category_id { get; set; }
}
public class DBCategory
{
public int? CategoryId { get; set; }
public string CategoryName { get; set; }
public int? CategoryParentId { get; set; }
public static List<DBCategory> GetChildren(Category catgory, int? parentId)
{
List<DBCategory> results = new List<DBCategory>() { new DBCategory() {
CategoryId = catgory.category_id,
CategoryName = catgory.name,
CategoryParentId = parentId
}};
if (catgory.children != null)
{
foreach (Category child in catgory.children)
{
results.AddRange(GetChildren(child, catgory.category_id));
}
}
return results;
}
}
}

How to add nodes to my Child/Parent object?

I have an object below:
public class SubjectCategory : BaseModel
{
public decimal ParentSubjectCategoryId { get; set; }
public bool IsEnable { get; set; }
public virtual List<Subject>? Subjects { get; set; }
public virtual List<SubjectCategory>? ChildrenCategoris { get; set; }
public virtual SubjectCategory? ParentCategory { get; set; }
}
I get lists of subjectCategories from database (Picture Below).
I wrote a method that it adds ChildrenCategoris inside the categories which their ParentSubjectCategory Id is NULL or 0, but the problem is it is only works for the first level of tree!
public List<SubjectCategory> GetAllSubjectCategories()
{
var res = _subjectCategoryRepository.Select(new SubjectCategory {}).ToList();
List<SubjectCategory> newSubjectCategory = new List<SubjectCategory>();
foreach (var item in res)
{
if(item.ParentSubjectCategoryId != 0)
{
var a = newSubjectCategory.Where(sc => sc.Id ==
item.ParentSubjectCategoryId).FirstOrDefault();
if(a.ChildrenCategoris == null)
{
newSubjectCategory.Where(sc => sc.Id ==
item.ParentSubjectCategoryId).FirstOrDefault().ChildrenCategoris = new List<SubjectCategory>() { item};
}
else
{
newSubjectCategory.Where(sc => sc.Id == item.ParentSubjectCategoryId).FirstOrDefault().ChildrenCategoris.Add(item);
}
}
else
{
newSubjectCategory.Add(item);
}
}
return res;
}
But every child can have many ChildrenCategoris and their children can have many ChildrenCategoris as well and again.
the loop count is unknown.
how can I have a list with multiple children with C# ?

Nested List Of Class Search Or Update Using Linq C#

How can I find class from nested list ?
I am working on trees and just want to retreive and add child based on id.
Class
public class d3_mitch
{
public int id { get; set; }
public string name { get; set; }
public string type { get; set; }
public string description { get; set; }
public List<d3_mitch> children { get; set; }
}
Object Creation and Query
d3_mitch t = new d3_mitch();
t.id = 1;
t.type = "Root";
t.name = "Animal";
t.description = "A living organism that feeds on organic matter";
t.children = new List<d3_mitch>() {
new d3_mitch() { name = "Carnivores", type = "Type", id = 2, description = "Diet consists solely of animal materials",
children=new List<d3_mitch>(){ new d3_mitch() { id= 3 ,name="Felidae",type="Family",description="Also known as cats"} }
}
};
d3_mitch child = t.children.Where(x => x.id == 3).FirstOrDefault();
//This return null because no direct child has has id = 3 but nested
You need to use recursion. Try next code
d3_mitch FindById(d3_mitch root, int id)
{
if (root.id == id)
return root;
foreach (var child in root.children)
{
if (child.id == id)
return child;
var subTreeResult = FindById(child, id);
if (subTreeResult != null)
return subTreeResult;
}
// no such item
return null;
}
Use SelectMany
t.children.SelectMany(s => s.children)
.FirstOrDefault(s => s.children.Any(d => d.id == 3));
Using a recursive method will resolve your problem.
public static d3_mitch Find(d3_mitch main, int id)
{
if (main.id == id)
return main;
if (main.id != id && main.children != null)
{
foreach (var child in main.children)
{
return child.children.Any(x=>x.id==id)? child.children.First(x=>x.id==id) : Find(child, id);
}
}
return null;
}

Linq query for the Multi list in singe out put

i have table looks like below
ID | Reason | PrID
-----------------
1 abc null
2 dhe null
3 aerc 1
4 dwes 2
5 adfje 1
i have class
public class Reason
{
public int Id { get; set; }
public string Reson{ get; set; }
public List<SecondryReason> SecReason{ get; set; }
public int? PrimaryId { get; set; }
}
public class SecondryReason
{
public int Id { get; set; }
public string Reason { get; set; }
public int PrimaryReasonId { get; set; }
}
I want this to be displayed in hierarchy level
if the prid is Null need to treat this as the parent remaining all child
i am trying Linq and unable to achieve this
Suggest me how to do this in an easy way in linq
So: You have a list/enumerable of type , whereof the SecReason List property is null. Then, using linq you want a list, were the only the "root" reasons remain, but the Sub-reasons got put in the lists, but as type SecondaryReason?
If so, I found this way to do it (linq and foreach):
static IEnumerable<Reason> GetReasonsGrouped(List<Reason> reasons)
{
var result = reasons.Where(x => x.PrimaryId == null);
foreach (var item in result)
{
item.SecReason = reasons.Where(x => x.PrimaryId == item.Id)
.Select(x => new SecondryReason()
{ Id = x.Id,
ReasonName = x.ReasonName,
PrimaryReasonId = item.Id
})
.ToList();
}
return result;
}
Or just linq, but harder to read:
var result = reasons.Where(x => x.PrimaryId == null)
.Select(x =>
{
x.SecReason = reasons.Where(r => x.PrimaryId == x.Id)
.Select(r => new SecondryReason()
{
Id = r.Id,
ReasonName = x.ReasonName,
PrimaryReasonId = x.Id
})
.ToList();
return x;
});
Not sure if linq will be the best solution, here is my proposed changes and method to get an Hierarchy type:
public class Reason
{
public int Id { get; set; }
public string Reson { get; set; }
public List<Reason> SecReason { get; set; }
public int? PrimaryId { get; set; }
//Adds child to this reason object or any of its children/grandchildren/... identified by primaryId
public bool addChild(int primaryId, Reason newChildNode)
{
if (Id.Equals(primaryId))
{
addChild(newChildNode);
return true;
}
else
{
if (SecReason != null)
{
foreach (Reason child in SecReason)
{
if (child.addChild(primaryId, newChildNode))
return true;
}
}
}
return false;
}
public void addChild(Reason child)
{
if (SecReason == null) SecReason = new List<Reason>();
SecReason.Add(child);
}
}
private List<Reason> GetReasonsHierarchy(List<Reason> reasons)
{
List<Reason> reasonsHierarchy = new List<Reason>();
foreach (Reason r in reasons)
{
bool parentFound = false;
if (r.PrimaryId != null)
{
foreach (Reason parent in reasonsHierarchy)
{
parentFound = parent.addChild(r.PrimaryId.Value, r);
if (parentFound) break;
}
}
if (!parentFound) reasonsHierarchy.Add(r);
}
return reasonsHierarchy;
}

EntityFramework 5 CodeFirst Child Parent of the Same Type Not Updating/Saving

I have a class called Section
public class Section
{
public Section() { construct(0); }
public Section(int order) { construct(order); }
private void construct(int order)
{
Children = new List<Section>();
Fields = new List<XfaField>();
Hint = new Hint();
Order = order;
}
[Key]
public int Id { get; set; }
public int FormId { get; set; }
public string Name { get; set; }
[InverseProperty("Parent")]
public List<Section> Children { get; set; }
public List<XfaField> Fields { get; set; }
public Section Parent { get; set; }
public Hint Hint { get; set; }
public int Order { get; private set; }
#region Methods
public void AddNewChild()
{
AddChild(new Section
{
Name = "New Child Section",
FormId = FormId,
});
}
private void AddChild(Section child)
{
child.Parent = this;
if (Children == null) Children = new List<Section>();
int maxOrder = -1;
if(Children.Count() > 0) maxOrder = Children.Max(x => x.Order);
child.Order = ++maxOrder;
Children.Add(child);
FactoryTools.Factory.PdfSections.Add(child);
}
// Other methods here
#endregion
}
I am trying to add a new child Section to an already existing parent like this:
private void AddChildSection()
{
var parent = FactoryTools.Factory.PdfSections.FirstOrDefault(x => x.Id == ParentId);
if (parent == null) throw new Exception("Unable to create child because parent with Id " + ParentId.ToString() + " doesn't exist.");
parent.AddNewChild();
FactoryTools.Factory.SaveChanges();
}
When I look at the database, I see that a new row has been added, so for example:
Id Name Parent_Id Hint_Id FormId Order
19 New Child Section 1 27 1 0
However, when I load the parent Section, the Children property is always of Count 0, like this:
public ActionResult EditSection(int formId, int sectionId)
{
var model = FactoryTools.Factory.PdfSections.FirstOrDefault(x => x.Id == sectionId);
if (model == null || model.FormId != formId) model = new Section();
//model.Children = FactoryTools.Factory.PdfSections.Where(x => x.Parent.Id == sectionId).ToList();
return PartialView(model);
}
Of course, when I manually add the children, then they are there (in the above code, by uncommenting the model.Children = ... line)
I am used to the NHibernate way of doing things and am therefore quite frustrated that the above, seemingly simple, task is not working in EntityFramework, what am I doing wrong?
Entity Framework won't eagerly load related entities. Try forcing it to include the children:
var model = FactoryTools.Factory.PdfSections.Include("Children").FirstOrDefault(x => x.Id == sectionId);
There's also a strongly-typed overload to which you can pass a lambda:
var model = FactoryTools.Factory.PdfSections.Include(s => s.Children).FirstOrDefault(x => x.Id == sectionId);

Categories