How to get around this tree

Some time has passed since I had to go through the tree and I need some input. Here is an example of a tree:

tree

The tree is my ASP.NET page. This page is made up of 2 main pages and a content page. What I want to do is find the control, which is my main main content of the main page, and then put all the controls inside in a flat data structure, such as a list.

So, if the orange node is the second main page of the ContentPlaceHolder, I would like to keep all those that are in the blue ellipse in my list. I already created some code to return me all the children, grandson, etc. The control in the collection using this:

private IEnumerable<Control> GetChildControls(Control parentControl) { foreach (Control control in parentControl.Controls) { yield return control; foreach(Control grandchild in GetChildControls(control)) { yield return grandchild; } } } 

But I'm a little fixated on how to filter this tree for node and its children. If this helps, the orange node should be as follows:

 <asp:Content ID="SystemMasterMainContentPlaceHolder" runat="server" ContentPlaceHolderID="MainContentPlaceholder"> 
+4
source share
1 answer

Basically, you can use a combination of the method that you already have and the GetChildById() method.

 private Control GetChildById(string controlId, Control parent) { return GetChildControls(parent).First(c => c.ID == controlId); } 

This is the reuse of tree traversal performed by GetChildControls . Note that it throws an exception if the control is not found - if you do not want this, use FirstOrDefault instead of First .

You can use it like this:

 GetChildControls(GetChildById("SystemMasterMainContentPlaceHolder", Page)); 
+2
source

Source: https://habr.com/ru/post/1468773/


All Articles