我在我的一個需求中實現了遞歸。我的實際需求如下: -如何從遞歸遞歸函數
有一個主表名爲庫存,它有許多記錄,比如說「庫存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