在 C# 中查找树项

Find tree item in c#

我有一个页面,用户可以在其中从 Xamarin Forms 的树层次结构中 select child 或 child。保存后,一旦用户单击编辑按钮,我需要遍历所有项目以再次设置用户的 selected 值

例如:

public class A
{
public string Id {get;set;}
public string Name {get;set;}
public List<A> Items{get;set;}
}

在虚拟机中,我有一个方法来初始化 A 类型的 object A1。我需要遍历 A 的所有 children 来匹配 A 的值和select编辑 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 的第一个 child 上循环。因此,谁能为我提供更好的解决方案?

问题是,当 a.Id != ida.Items.Count > 0 时,您没有进一步迭代列表中的其他项目。您应该保存递归 GetA 的结果,并且只有当它不为 null return 时才保存它,否则继续循环。否则你会循环直到第一个分支,然后递归地只搜索所有第一个分支,而不是任何其他分支。

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;
}