I’m trying to update an item inside my object graph which could span ‘n’ level in depth.
The following is my object model:
public class Entity
{
public string Name { get; set; }
}
public class Category : Entity
{
public List<Category> Categories { get; set; }
public List<Product> Products { get; set; }
}
public class Product : Entity
{
}
My view is bound to an ObservableCollection<Category> Categories. What I want to do is given a category name, I need to retrieve the first object which matches that from the collection.
For ex, given a list like this and a category Facial Tissue, I need to retrieve the Facial Tissue category object from the collection.
Category - Pharmacy
|-Product - Aspirin
|-Product - Tylenol
|-Category - Tooth Paste
| |-Product - Crest
| |-Product - Colgate
|-Category - Paper Products
|-Category - Toilet Paper
| |-Product - NoName
| |-Product - Charmin
|-Category - Facial Tissue
|-Product - Kleenex
Category - Household
|-Product - Pinesol Cleaner
|-Product - Garbage Bags
I have tried this, but it throws an Object reference not set to an instance of an object exception when I search level >2 in the hierarchy.
return Categories.FirstOrDefault(n => n.Name == name) ??
Categories.SelectMany(node => node.Categories).Where(lx => lx.Name == name).FirstOrDefault();
NOTE: At times the categories could be null deep down the hierarchy.i.e if there are no categories, then the collection is set to null.Also the solution necessarily need not be using LINQ.
You can use either of the following methods to traverse the tree structure recursively:
There is an overload for a single root item, and another that takes a sequence of items.
You could implement them using actual recursion if you prefer, but I prefer an explicit data structure. If you would like a depth first search instead of a breath first search just change the
Queueto aStackand update the methods accordingly.To use it you can do something like this:
It also appears that you’re getting null errors because you have
Categoriesthat are null. If at all possible, I would highly encourage you to fix that problem, rather than dealing with it. If an Entity has no Categories it should have an empty list, not a null list. Having said that, you can adjust theTraversecalls as follows if you have any null items: