我有一個頁面,用戶可以在其中從 Xamarin Forms 的樹層次結構中選擇一個孩子的孩子。保存后,一旦用戶單擊編輯按鈕,我需要遍歷所有專案以再次設定用戶選擇的值
例如:
public class A
{
public string Id {get;set;}
public string Name {get;set;}
public List<A> Items{get;set;}
}
在 VM 中,我有一個方法來初始化 A 型別的物件 A1。我需要遍歷 A 的所有子物件以將 A 的值與所選 Id 的值匹配
private A GetA(string id, List<A> items)
{
foreach (var a in items)
{
if (a.Id == id)
{
return a;
}
else
{
if (a.Items.Count > 0)
{
return GetA(id, a.Items);
}
}
}
return null;
}
到目前為止,我寫了一個遞回函式,它只在每個 A 的第一個孩子上回圈。因此,誰能給我一個更好的解決方案?
uj5u.com熱心網友回復:
問題是,您沒有進一步迭代串列中的其他專案,whena.Id != id和a.Items.Count > 0. 相反,您應該保存遞回的結果,GetA并且僅當它不為空時才回傳它,否則繼續回圈。否則你只會回圈直到第一個分支,然后遞回地只搜索所有第一個分支,而不是任何其他分支。
private A GetA(string id, List<A> items)
{
foreach (var a in items)
{
if (a.Id == id)
{
return a;
}
// You could also remove this if and just call GetA directly,
// since GetA(id, a.Items) with an empty list,
// will always return null
if (a.Items.Count > 0)
{
var innerA = GetA(id, a.Items);
if (innerA != null) {
return GetA(id, a.Items);
}
}
}
return null;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/483192.html
標籤:C#
