要獲得所有的孩子:
public IEnumerable<long> GetChildren(List<Channel> list, long id)
{
foreach(Channel c in list)
if(c.parentID == id)
yield return c.ID;
}
構建這是返回一個IEnumerable<long>
而不是返回,需要一個List<long>
可以使用new List<long>(GetChildren(list, id))
或GetChildren(list, id).ToList()
,同時調用代碼並不需要一個List<long>
作爲然後調用代碼這可以在內存和時間上獲得更好的性能,通過不建立它實際上不需要的列表而獲得第一個結果,如foreach(long childID in GetChildren(list, id))
。
要獲得所有後代(子女,孫子,曾孫等),這是唯一的情況下,我們可以讓任何使用遞歸(根據你的問題的標題)使用方法:
假設有不能重複(通過多種途徑相同的孫子):
private IEnumerable<long> GetDescendants(List<Channel> list, long id)
{
foreach(long child in GetChildren(list, id))
{
yield return child;
foreach(long grandchild in GetDescendants(list, child))
yield return grandchild;
}
}
如果可以有重複,那麼你可以申請.Distinct()
以上,或去:
private IEnumerable<long> GetDescHelper(List<Channel> list, long id, HashSet<long> already)
{
foreach(long child in GetChildren(list, id))
if(already.Add(child))
{
yield return child;
foreach(long desc in GetDescHelper(list, child, already))
yield return desc;
}
}
public IEnumerable<long> GetDescendants(List<Channel> list, long id)
{
return GetDescHelper(list, id, new HashSet<long>());
}
這就是說,我可能更願意讓Channel類保持List<Channel>
的孩子。
你想要孩子的孩子嗎?請爲樣本數據添加一個等級並列出所需的輸出。 –
重複ID 28,這是錯誤的嗎? –
如果'Channel'有一個'List Children {get;私人設置; }'? –
Oliver