【问题标题】:How to write recursion on loop properly?如何正确编写循环递归?
【发布时间】:2021-01-18 09:37:36
【问题描述】:

我有这样的List<IRequest>

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

如何找到RequestIsSelected对象?

假设我有这样的结构

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

我写了这样的方法

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

            return null;
        }

但它只在第一行进行迭代,如果我选择的项目位于第二行,我的方法将返回 null。

我做错了什么?

【问题讨论】:

  • edit 并标记一种语言 (c#?)
  • else中,只有return如果递归调用的结果不是null
  • @JohnnyMopp 你的第二条评论是什么意思?

标签: c# asp.net recursion


【解决方案1】:

else 中,仅当递归调用的结果不是null 时才返回,因为在当前子列表中没有找到它并不一定意味着它不在某个其他子列表中。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 2020-04-29
    • 2021-08-11
    • 1970-01-01
    相关资源
    最近更新 更多