【问题标题】:How can I search the tree structure in LINQ or some other way如何在 LINQ 或其他方式中搜索树结构
【发布时间】:2019-07-25 07:00:14
【问题描述】:
public interface IComponent
{
    Guid Key { get; set; }
}
 public interface ICanHaveChildElement
{
    List<IComponent> ChildElement {get;set;}
}
public class BaseComponent : IComponent
{
    public Guid Key { get; set; }
}
public class TextBox : BaseComponent, IComponent
{

}
public class Radiobutton : BaseComponent, IComponent
{

}
public class Table : BaseComponent, IComponent, ICanHaveChildElement
{
    public List<IComponent> ChildElement { get; set; }
}
public class TestService
{
    public void Search(Guid key)
    {
        List<IComponent> components = new List<IComponent>();
        var element = components.FirstOrDefault(p => p.Key == key);
    }
}

你好,

如上所述,当我在现有代码块中没有子组件的组件(文本框、收音机等)中进行搜索时,我可以找到该组件。 但是,我找不到带有子组件的组件,例如表格。用if检查可以找到,但由于不知道它会有多少个子组件,所以只能用一个子元素操作成功。

我的问题是我想搜索整个列表的“关键”参数。即使具有此键的元素是子元素,我也想找到。

【问题讨论】:

    标签: c# asp.net linq asp.net-core tree-search


    【解决方案1】:

    你可以试试这样的:

    public IComponent Search(Guid key, IEnumerable<IComponent> components)
    {
        foreach (var c in components)
        {
            if (c.Key == key)
            {
                return c;
            }
            else if (c is ICanHaveChildElement withChildren)
            {
                return Search(key, withChildren.ChildElement);
            }
        }
    
        return null;
    }
    

    代码在循环中检查组件键是否等于您要查找的键。如果没有,它会检查组件是否实现了“有子”接口,如果是,则递归处理其子接口。

    请注意,如果您使用的是旧版本的 C#,“else if”中的模式匹配语句将无法编译,但可以轻松地将其替换为“as”强制转换并检查“not null”。

    【讨论】:

    • 也许你可以详细说明一下递归调用部分,因为 OP 可能是递归概念的新手
    【解决方案2】:
    public IComponent GetComponentByKey(Guid key, List<IComponent> components)
            {
                foreach (var c in components)
                {
                    if (c.Key.Equals(key)) return c;
                    else if (c is ICanHaveChildElement)
                    {
                        return GetComponentByKey(key, (c as ICanHaveChildElement).ChildElement);
                    }
                }
                return null;
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-11
      • 1970-01-01
      • 1970-01-01
      • 2018-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多