gpt4 book ai didi

c# - 使用递归 c# 实现以下方法

转载 作者:太空宇宙 更新时间:2023-11-03 17:57:57 25 4
gpt4 key购买 nike

<分区>

如何将以下方法更改为递归方法:

    public List<ScanItem> search(List<ScanItem> allItems)
{
List<ScanItem> rt = new List<ScanItem>();

foreach (ScanItem s in allItems)
{
if (s.IsDirectory)
{
rt.Add(s);



foreach (ScanItem s1 in ((ScanDir)s).Items)
{
if (s1.IsDirectory)
{
rt.Add(s1);




foreach (ScanItem s2 in ((ScanDir)s1).Items)
{
if (s2.IsDirectory)
{
rt.Add(s2);

foreach (ScanItem s3 in ((ScanDir)s2).Items)
{
if (s3.IsDirectory)
{
rt.Add(s3);

/// repeat until there are no more direcotries

}
else
if (s3.Name.Contains("Foo"))
rt.Add(s3);
}

}
else
if (s2.Name.Contains("Foo"))
rt.Add(s2);
}



}
else
if (s1.Name.Contains("Foo"))
rt.Add(s1);
}


}
else
if (s.Name.Contains("Foo"))
rt.Add(s);

}

return rt;

}

让我向您展示我是如何构建它的:

第一步:

    public List<ScanItem> search(List<ScanItem> allItems)
{
List<ScanItem> rt = new List<ScanItem>();

foreach (ScanItem s in allItems)
{
if (s.IsDirectory)
{
rt.Add(s);

}
else
if (s.Name.Contains("Foo"))
rt.Add(s);

}

return rt;

}

第二步:

    public List<ScanItem> search(List<ScanItem> allItems)
{
List<ScanItem> rt = new List<ScanItem>();

foreach (ScanItem s in allItems)
{
if (s.IsDirectory)
{
rt.Add(s);



foreach (ScanItem s1 in ((ScanDir)s).Items)
{
if (s1.IsDirectory)
{
rt.Add(s1);

}
else
if (s1.Name.Contains("Foo"))
rt.Add(s1);
}


}
else
if (s.Name.Contains("Foo"))
rt.Add(s);

}

return rt;

}

第 3 步:

    public List<ScanItem> search(List<ScanItem> allItems)
{
List<ScanItem> rt = new List<ScanItem>();

foreach (ScanItem s in allItems)
{
if (s.IsDirectory)
{
rt.Add(s);



foreach (ScanItem s1 in ((ScanDir)s).Items)
{
if (s1.IsDirectory)
{
rt.Add(s1);




foreach (ScanItem s2 in ((ScanDir)s1).Items)
{
if (s2.IsDirectory)
{
rt.Add(s2);

}
else
if (s2.Name.Contains("Foo"))
rt.Add(s2);
}



}
else
if (s1.Name.Contains("Foo"))
rt.Add(s1);
}


}
else
if (s.Name.Contains("Foo"))
rt.Add(s);

}

return rt;

}

第 4 步:

    public List<ScanItem> search(List<ScanItem> allItems)
{
List<ScanItem> rt = new List<ScanItem>();

foreach (ScanItem s in allItems)
{
if (s.IsDirectory)
{
rt.Add(s);



foreach (ScanItem s1 in ((ScanDir)s).Items)
{
if (s1.IsDirectory)
{
rt.Add(s1);




foreach (ScanItem s2 in ((ScanDir)s1).Items)
{
if (s2.IsDirectory)
{
rt.Add(s2);

foreach (ScanItem s3 in ((ScanDir)s2).Items)
{
if (s3.IsDirectory)
{
rt.Add(s3);

}
else
if (s3.Name.Contains("Foo"))
rt.Add(s3);
}

}
else
if (s2.Name.Contains("Foo"))
rt.Add(s2);
}



}
else
if (s1.Name.Contains("Foo"))
rt.Add(s1);
}


}
else
if (s.Name.Contains("Foo"))
rt.Add(s);

}

return rt;

}

请注意,我一直在复制:

                                foreach (ScanItem s3 in ((ScanDir)s2).Items)
{
if (s3.IsDirectory)
{
rt.Add(s3);

/// repeat until there are no more direcotries

}
else
if (s3.Name.Contains("Foo"))
rt.Add(s3);
}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com