Count depth of a hierarchy of classes

大兔子大兔子 提交于 2021-02-07 11:11:15

问题


I've seen a lot of different examples of how to do this and am well aware that I could write out a loop that iterates my entire tree of classes to find the maximum depth, but I cannot help but think there has to be a simpler way.

Basically I have two classes that I developed to host all my applications settings, SettingGroup which is exactly what it sounds like, basically a folder, and Setting which is the setting itself and the configurations that allow the application to know what the setting is for and how to display it. The reason I dont just use a fixed class and write out field for my settings is that the application is plugin driven and I wish the settings to remain centralized is plugins are added or removed and not have to worry about decentralized data from the plugins.

When dynamically creating the settings page it is necessary to know the maximum depth of any particular SettingGroup so I know if the root should first organized by tabs, pages, sections etc...

Long story short, is there a reasonably lightweight way to determine the groups maximum depth?

public enum DescriptionVisibility { None, SubText, ToolTip };
public enum SettingType { Bool, Integer, Decimal, Text };
public enum SettingControl { Checkbox, Textbox, Slider, Radio, Dropdown, TextField, Color};

public class SettingGroup
{
    public string name { get; set; }
    public string description { get; set; }
    public List<SettingGroup> groups { get; set; }
    public List<Setting> settings { get; set; }
}
public class Setting
{
    public string name { get; set; }
    public string description { get; set; }
    public DescriptionVisibility descriptionVisibility { get; set; }
    public Dictionary<string, dynamic> configuration { get; set; }
    public dynamic settingValue { get; set; }
    public SettingType settingType { get; set; }
    public SettingControl settingControl { get; set; }

}

Edit: this is untested, but this is what I am currently considering using;

    private static int getDepth(this SettingGroup group, int depth = 0)
    {
        if (group.groups == null)
            return depth;
        if (group.groups.Count == 0)
            return depth;

        int returnDepth = depth;

        foreach (SettingGroup subGroup in group.groups)
        {
            int subGroupDepth = subGroup.getDepth(depth + 1);
            if (subGroupDepth > returnDepth)
                returnDepth = subGroupDepth;
        }

        return returnDepth;
    }

Its pretty basic so it couldn't be TOO slow, but still seems bulky, is there not a LINQ way to do this perhaps?

来源:https://stackoverflow.com/questions/34819113/count-depth-of-a-hierarchy-of-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!