Find maximum depth/level of a nested collection
c#, linq, recursion, tree
Solution
Well you could easily turn it into an instance property, yes:
public int Depth
{
get
{
if (Items.Count == 0)
return 0;
var subMenu = Items.Select(b => b as MenuGroup);
if (!subMenu.Any())
return 1;
var subLevel = subMenu.Cast<MenuGroup>().Select(x = > x.Depth);
return !subLevel.Any() ? 1 : subLevel.Max() + 1;
}
}
That won't quite work yet due to the handling of non-`MenuGroup` items, but it can easily be fixed, using `OfType` instead of the `Select` and then `Cast`:
public int Depth
{
get
{
// Completely empty menu (not even any straight items). 0 depth.
if (Items.Count == 0)
{
return 0;
}
// We've either got items (which would give us a depth of 1) or
// items and groups, so find the maximum depth of any subgroups,
// and add 1.
return Items.OfType<MenuGroup>()
.Select(x => x.Depth)
.DefaultIfEmpty() // 0 if we have no subgroups
.Max() + 1;
}
}
Problem
I want to create a Property which can find the depth of the nested tree structure. The below static finds out the depth/level by recursion. But is it possible to make this function as a property in the same class instead of a static method? ``` public static int GetDepth(MenuGroup contextMenuItems) { if (contextMenuItems == null || contextMenuItems.Items.Count == 0) return 0; var subMenu = contextMenuItems.Items.Select(b => b as MenuGroup); if (!subMenu.Any()) return 1; var subLevel = subMenu.Cast<MenuGroup>().Select(GetDepth); return !subLevel.Any() ? 1 : subLevel.Max() + 1; } ``` Some more info on the code: MenuGroup and MenuItem are derived from MenuBase MenuGroup has children nodes with `ObservableCollection<MenuBase> Items` as Child Elements MenuItem is a leave node without any child.