Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

list - C# Recursive delete nodes

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...