我有一个页面,用户可以在其中从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的第一个子元素。因此,有人能给我一个更好的解决方案吗?问题是,当a.Id != id
和a.Items.Count > 0
时,您没有进一步遍历列表中的其他项。你应该保存递归GetA
的结果,只有当它不是null返回它,否则继续循环。否则,你就只能循环到第一个分支,然后递归地只搜索所有的第一个分支,而不搜索任何其他分支。
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;
}