1
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);
    }
}

Hello,

When I search within the components (Textbox, Radio, etc.) that do not have subcomponents in my existing code block as above, I can find the component. However, I cannot find components with subcomponents such as tables. I can find it by checking with if, but since I don't know how many sub-components it will have, it can only be successful in operations with one sub-element.

My question is "key" parameter I want to search the entire list. I want to find even if the element with this key is a sub-element.

Harun
  • 51
  • 1
  • 6

2 Answers2

1

You can try something like this:

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;
}

The code checks in the loop if components key is equal to what you are looking for. If not, it checks if the component implements "has children" interface and if yes - processes its children recursively.

Please note that if you are using older versions of C#, pattern-matching statement in "else if" won't compile, but it can be easily replaced with "as" casting and checking on "not null".

yurexus
  • 323
  • 1
  • 5
  • may be you could elaborate a little on the recursive call part, since OP is probably new to the concept of recursion – Mong Zhu Jul 25 '19 at 07:33
0
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;
        }
melody zhou
  • 148
  • 4