Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I created a class for hierarchical data. From this class I generate custom treeview. Before sending data to treeview I need delete a branch that does not end with instance with HaveData = true

    public class Data
    {
        public List<Data> Children
        {
            get;
            set;
        }

        public bool HaveData
        {
            get;
            set;
        }
    }

Treeview before:

1 First
1.1 Item
1.1.1 Item (HaveData = false)
1.2 Item
1.2.1 Item (HaveData = true)
...

I need:

1 First
1.2 Item
1.2.1 Item (HaveData = true)
...

How to go through all nodes and remove only those that ending HaveData = false? Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
263 views
Welcome To Ask or Share your Answers For Others

1 Answer

Here is one recursive way to do it:

public void DeleteBranchWithNoData()
{
    var toBeRemoved = new List<Data>();
    foreach(var child in Children)
    {
        if(!child.HaveData && (child.Children == null || !child.Children.Any()))
        {
            toBeRemoved.Add(child);
        }
        else
        {
            child.DeleteBranchWithNoData();
        }   
    }
    Children.RemoveAll(d => toBeRemoved.Contains(d));
}

Call this method from the top node of the branch you want to delete.

You can see a live demo on rextester.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...