0

I have such List<IRequest>

public interface IRequest
    {
        List<IRequest> Childrens { get; set; }
        bool RequestIsSelected { get; set; }
    }

How to find RequestIsSelected object?

Let's say I have such structure

IRequest -
          |
          IRequest - 
                    |
                     IRequest  <--- if this one is true I can catch it
          |
          IRequest -
                    |
                     IRequest   <----- This one RequestIsSelected == true;  (I can't catch it)

I wrote such method

private IRequest GetSelectedItem(List<IRequest> entireList)
        {
            foreach(var tmp in entireList)
            {
                if(tmp.RequestIsSelected)
                {
                    return tmp;
                }
                else
                {
                    return GetSelectedItem(tmp.Childrens);
                }
            }

            return null;
        }

But it iterates only on first deep line, if my selected item resides in second line my method returns null.

What am I doing wrong?

3
  • Please edit and tag a language (c#?) Commented Oct 2, 2020 at 17:51
  • In the else, only return if the result of the recursive call is not null. Commented Oct 2, 2020 at 17:56
  • @JohnnyMopp what do you mean about your second comment? Commented Oct 2, 2020 at 17:58

1 Answer 1

1

In the else, only return if the result of the recursive call is not null since not finding it in the current child does not necessarily mean it is not in some other child list.

private IRequest GetSelectedItem(List<IRequest> entireList)
{
    if (entireList == null) return null;

    foreach(var tmp in entireList)
    {
        if(tmp.RequestIsSelected)
        {
            return tmp;
        }
        else
        {
            IRequest child = GetSelectedItem(tmp.Childrens);
            if (child != null) return child; 
            // Else keep searching since it may
            // be in some other child list
        }
    }

    return null;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.