Home > Mobile >  Find tree item in c#
Find tree item in c#

Time:05-31

I have a page in which a user can select a child of a child from a tree hierarchy in Xamarin Forms. After saving, once a user clicks the edit button, I need to loop over all the items to set the user's selected value again

For example:

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

In the VM, I have a method to initialize object A1 of type A. I need to loop over all the children of A to match a value of A to that of the selected 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;
}

So far, I wrote a recursive function that only loops on the first child of every A. Thus, can anyone provide me with a better solution?

CodePudding user response:

The problem is, that you are not further iterating over the other items in the list, when a.Id != id and a.Items.Count > 0. You should instead save the result of the recursive GetA and only if it's not null return it, otherwise keep looping. Otherwise you would just loop until the first branch and then recursively only ever search all the first branches, but not any other ones.

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;
}
  •  Tags:  
  • c#
  • Related