c# - 寻找递归路径
问题描述
大家好,我有一个小问题,我感觉有点卡住了。我设法获得了我想要的对象,但我不知道如何返回该对象的路径(我是如何找到它的)。我的代码现在看起来像这样:
PS我的意思是路径:每个项目都有它的名称和ID。我设法找到一个带有 id 的对象(我在调用递归时给出),当我找到它时,我需要创建字符串并将它的所有父名称添加到它并返回它。
protected void FindPath(int depth, int id, InventLocationViewModel currentLocation)
{
if (depth < 0)
return;
if (currentLocation.Id == id)
{
selectedLocation = currentLocation;
return;
}
foreach (var child in currentLocation.ChildInventLocations)
{
FindPath(depth - 1, id, child);
}
}
protected void SelectedLocation(RecursiveSelectObject args)
{
currentLocation = locations.InventLocations.FirstOrDefault(e => e.Id == locationId.Value);
FindPath(args.Level, args.Id, currentLocation);
if (selectedLocation.Id == args.Id)
{
}
}
解决方案
您知道在退出过程中要保留的内容:
protected List<InventLocationViewModel> FindPath(int id, InventLocationViewModel currentLocation)
{
if (currentLocation.Id == id)
{
return new List<InventLocationViewModel> {currentLocation};
}
foreach (var child in currentLocation.ChildInventLocations)
{
var result = FindPath(id, child);
if (result != null)
{
result.Add(currentLocation);
return result;
}
}
return null;
}
推荐阅读
- javascript - 一次通话两种不同的内容类型
- google-apps-script - 如何将谷歌文档转换为干净的 HTML
- apache-kafka - 如何自动调用 kafka-stream-processor 中的 process() 方法?
- java - 由动画关键帧引起的除零异常 (LIBGDX)
- angular - 数组更改时刷新 ng2-smart-table
- python - 将多个值添加到列中 - Pandas
- ios - 从我的本机应用程序将 cookie 传递给 SFSafariViewController
- html - Dreamweaver 不加载缓存克星 css
- python - Python将var初始化为None?
- javascript - 如何在 React Native 中调用函数