我在我的一个需求中实现了递归。我的实际需求如下: -如何从递归递归函数
有一个主表名为库存,它有许多记录,比如说“库存A”,“库存B”,“库存C”。
还有一个表叫做库存包它链接一个库存与其他。所以库存包表具有两列: - 代表源库存Id和目标库存ID的TI & TI。
Record Ex。
SI TI
A B
B C
在,如果我点击任何库存,则关联的库存也应取了我的要求。
像这里一样,如果我点击B然后A & C应该被取出。我使用以下递归方法来获得要求: -
List<Guid> vmAllBundle = new List<Guid>();
List<Guid> vmRecursiveBundle = new List<Guid>();
List<Guid> processedList = new List<Guid>();
public List<Guid> GetAllRecursiveBundle(Guid invId, Guid originalInvId)
{
List<Guid> vmInvSrcBundleList = GetSourceInventory(invId); //Fetch to get All Related Source Inventories
List<Guid> vmInvTarBundleList = GetTargetInventory(invId); //Fetch to get All Related Target Inventories
vmAllBundle.AddRange(vmInvSrcBundleList);
vmAllBundle.AddRange(vmInvTarBundleList);
if (vmAllBundle.Contains(originalInvId))
vmAllBundle.Remove(originalInvId);
vmAllBundle = vmAllBundle.Distinct().ToList();
vmRecursiveBundle = vmAllBundle.ToList().Except(processedList).ToList();
foreach (Guid vmInvBundle in vmRecursiveBundle)
{
vmRecursiveBundle.Remove(vmInvBundle);
processedList.Add(vmInvBundle);
GetAllRecursiveBundle(vmInvBundle, originalInvId);
if (vmRecursiveBundle.Count == 0)
return vmAllBundle;
}
return null;
}
我能够使用此方法获取数据,但我在返回时遇到问题。
当我返回时,它调用GetAllRecursiveBundle()并使用foreach循环并继续调用,直到vmAllBundle中的所有项都完成为止。之后它退出递归。
这是我的新东西,所以张贴问题,问这是正常行为还是一些代码逻辑必须改变。
修改代码
public List<Guid> GetAllRecursiveBundle(Guid invId, Guid originalInvId)
{
if (vmRecursiveBundle.Count > 0)
vmRecursiveBundle.Remove(invId);
List<Guid> vmInvSrcBundleList = GetSourceInventory(invId); //Fetch to get All Related Source Inventories
List<Guid> vmInvTarBundleList = GetTargetInventory(invId); //Fetch to get All Related Target Inventories
vmAllBundle.AddRange(vmInvSrcBundleList);
vmAllBundle.AddRange(vmInvTarBundleList);
if (vmAllBundle.Contains(originalInvId))
vmAllBundle.Remove(originalInvId);
vmAllBundle = vmAllBundle.Distinct().ToList();
vmRecursiveBundle = vmAllBundle.ToList().Except(processedList).ToList();
foreach (Guid vmInvBundle in vmRecursiveBundle)
{
processedList.Add(vmInvBundle);
GetAllRecursiveBundle(vmInvBundle, originalInvId);
if (vmRecursiveBundle.Count == 0)
break;
}
return vmAllBundle;
}
是代码无限期运行?它永远不会结束吗? –
嗨德文,即使最初也没有无限的时间。我修改了代码。 – user1843970
是否必须在递归方法内完成从表中获取数据?我认为如果递归方法只接受选定的清单及其之间的关系,那么递归方法实现起来会简单得多。 – Poosh