سؤال

I am trying to traverse a tree sructure defined as follows

public class TreeItem
{
    string _Name;
    public string Name
    {
        get { return _Name; }
        set { _Name = value; }
    }

    bool _IsChecked;
    public bool IsChecked
    {
        get { return _IsChecked; }
        set { _IsChecked = value; }
    }

    Visibility _CheckBoxVisibility;
    public Visibility CheckBoxVisibility
    {
        get { return _CheckBoxVisibility; }
        set { _CheckBoxVisibility = value; }
    }

    Visibility _ImageVisibility;
    public Visibility ImageVisibility
    {
        get { return _ImageVisibility; }
        set { _ImageVisibility = value; }
    }

    List<TreeItem> _Children;
    public List<TreeItem> Children
    {
        get { return _Children; }
        set { _Children = value; }
    }

    public TreeItem()
    {
        Children = new List<TreeItem>();
        IsChecked = true;
        CheckBoxVisibility = Visibility.Collapsed;
    }

    public TreeItem(TreeItem t)
    {
        Children = t.Children;
        Name = t.Name;
    }

    public void AddChild(TreeItem _Child)
    {
        Children.Add(_Child);
    }

}

Func delegate declaration

Func<TreeItem, TreeItem> Traverse = null;
Traverse = (t) => (t.Children.Count == 0) ? t : Traverse(t) ;

But when i Invoke it is give a stackoverflow expception, i know it is caused by passing t again to Travese resulting in an infinite loop. I wanted a solution by which somehow i can pass Children property instead of the entire class object to Travese.

هل كانت مفيدة؟

المحلول

I think that will do it:

Traverse = (t) => (t.Children.Count == 0) ? t : Traverse(t.Children[0]) ;

نصائح أخرى

Traverse = t => t.Children.ForEach(Traverse);

This will traverse the whole tree if used on the root. It will not have any return value though. Possible ways you could check:

TraverseAndCheckIfAnyIsChecked = t => t.IsChecked || t.Children.Any(TraverseAndCheckIfAnyIsChecked);


TraverseAndCheckIfAllAreChecked = t => t.IsChecked && t.Children.All(TraverseAndCheckIfAallAreChecked);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top