logo
down
shadow

Get a property from each level of a tree structure


Get a property from each level of a tree structure

By : user2954005
Date : November 21 2020, 07:31 AM
Does that help I have a list of objects in which each object in the list potentially has another list of the same type below it (a pretty standard tree structure). I am looking for a way to generically pull a property from every level this tree (since i want to potentially pull several of them) into a flattened list. , I believe this is what you are looking for.
code :
public static IEnumerable<T> FlattenProperty<T>(this Group g, Func<Group,T> transform)
{
    yield return transform(g);
    foreach(var item in g.SubGroups.SelectMany(sub => sub.FlattenProperty(transform)))
       yield return item;
}
public static IEnumerable<T> FlattenProperty<T>(
    this IEnumerable<Group> groups, 
    Func<Group,T> transform)
{
    foreach(Group g in groups)
    {
        yield return transform(g);
        foreach(var item in g.SubGroups.FlattenProperty(transform))
            yield return item;
    }
}


Share : facebook icon twitter icon
In a tree data structure, display tree nodes level by level

In a tree data structure, display tree nodes level by level


By : H0ppus
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further If you're feeling brutish, and want to think very simply about the level you are at...
You will need:
Level Order tree Traversal for a generic tree, displaying the tree level by level

Level Order tree Traversal for a generic tree, displaying the tree level by level


By : Ad Wolters
Date : March 29 2020, 07:55 AM
Any of those help I would like to display the tree structure level by level. My current code does a BFS or Level Order Traversal but I cannot get the output to display the tree structure like a tree See current output and Expected output. , only need to keep track of current level and next level.
code :
static void displayBFS(NaryTreeNode root) {
    int curlevel = 1;
    int nextlevel = 0;

    LinkedList<NaryTreeNode> queue = new LinkedList<NaryTreeNode>();
    queue.add(root);

    while(!queue.isEmpty()) { 
        NaryTreeNode node = queue.remove(0);

        if (curlevel == 0) {
            System.out.println();
            curlevel = nextlevel;
            nextlevel = 0;
        }

        for(NaryTreeNode n : node.nary_list) {
            queue.addLast(n);
            nextlevel++;
        }

        curlevel--;
        System.out.print(node.data + " ");
    } 
}
Tree structure: validating depth level of tree

Tree structure: validating depth level of tree


By : Andersson Galves de
Date : March 29 2020, 07:55 AM
Any of those help Looks like no one can help me (apart from pointing out typo errors) so I figured out it by myself. It's little bit ugly solution but it works like I want:
code :
private function validateTree($tree)
    {
        foreach($tree as $node)
        {
            $parentName = $node['title'];
            if(isset($node['children']) and is_array($node['children']))
            {
                if((bool)$node = $this->validateLevel($node['children']))
                {
                    $this->errors[] = $node;
                }
            }
            else
            {
                $this->errors[] = $node;
            }
        }
    }

    private function validateLevel($nodes)
    {
        foreach($nodes as $node)
        {
            if(isset($node['children']) and (bool)$node['children'] and is_array($node['children']))
            {
                foreach($node['children'] as $nodeLvl3)
                {
                    if(isset($nodeLvl3['children']) and (bool)$nodeLvl3['children'] and is_array($nodeLvl3['children']))
                    {
                        foreach($nodeLvl3['children'] as $nodeLbl)
                        {
                            //everything is OK
                        }
                    }
                    else
                    {
                        $this->errors[] = 'Category'.$nodeLvl3['title'].' does not have lvl 4';
                    }
                }
            }
            else
            {
                $this->errors[] = 'Category'.$node['title'].' does not have lvl 3';
            }
        }
    } 
how to append child level and grand child level json data into tree view structure

how to append child level and grand child level json data into tree view structure


By : Viletempest
Date : March 29 2020, 07:55 AM
this one helps. I want to append json data to bring tree view structure. Initially I had created static tree view this is my fiddle code with json tree view: , I figured it out check this-
code :
var json = {
    "category": [{
        "title": "Customer Satisfaction",
        "id": "nnanet:category/certified-pre-owned",
        "items": [{
            "title": "Bulletins",
            "id": "nnanet:category/customer-satisfaction/bulletins",
            "thirditems": [{
                "title": "TOI",
                "id": "nnanet:category/retailer-digital-marketing/toi"
            }, {
                "title": "TOI",
                "id": "nnanet:category/retailer-digital-marketing/toi"
            }]
        }, {
            "title": "Consumer Affairs",
            "id": "nnanet:category/customer-satisfaction/consumer-affairs"
        }, {
            "title": "Loyalty",
            "id": "nnanet:category/customer-satisfaction/loyalty",
            "thirditems": [{
                "title": "TOI",
                "id": "nnanet:category/retailer-digital-marketing/toi"
            }, {
                "title": "TOI",
                "id": "nnanet:category/retailer-digital-marketing/toi"
            }]
        }]
    }, {
        "title": "Retailer Digital Marketing",
        "id": "nnanet:category/retailer-digital-marketing",
        "items": [{
            "title": "TOI",
            "id": "nnanet:category/retailer-digital-marketing/toi",
            "thirditems": [{
                "title": "TOI",
                "id": "nnanet:category/retailer-digital-marketing/toi"
            }, {
                "title": "TOI",
                "id": "nnanet:category/retailer-digital-marketing/toi"
            }]
        }, {
            "title": "Basics",
            "id": "nnanet:category/retailer-digital-marketing/reference-guide/basics"
        }, {
            "title": "International",
            "id": "nnanet:category/retailer-digital-marketing/international"
        }]
    }, {
        "title": "Finance Today",
        "id": "nnanet:category/customer-satisfaction/bulletins/finance-today",
        "items": [{
            "title": "TOI",
            "id": "nnanet:category/retailer-digital-marketing/toi",
            "thirditems": [{
                "title": "TOI",
                "id": "nnanet:category/retailer-digital-marketing/toi"
            }, {
                "title": "TOI",
                "id": "nnanet:category/retailer-digital-marketing/toi"
            }]
        }, {
            "title": "Basics",
            "id": "nnanet:category/retailer-digital-marketing/reference-guide/basics"
        }, {
            "title": "International",
            "id": "nnanet:category/retailer-digital-marketing/international"
        }]
    }, {
        "title": "Annual",
        "id": "nnanet:category/customer-satisfaction/bulletins/finance-today/revenue/annual",
        "items": [{
            "title": "TOI",
            "id": "nnanet:category/retailer-digital-marketing/toi"
        }, {
            "title": "Basics",
            "id": "nnanet:category/retailer-digital-marketing/reference-guide/basics"
        }, {
            "title": "International",
            "id": "nnanet:category/retailer-digital-marketing/international"
        }]
    }]
};
    function expander(){
        var tree = document.querySelectorAll('ul.tree a:not(:last-child)');
    for(var i = 0; i < tree.length; i++){
        tree[i].addEventListener('click', function(e) {
            var element = e.target.parentElement; //actually this is just the elem itself
            var parent = element.parentElement

            var opensubs = parent.querySelectorAll(':scope .open');
            console.log(opensubs);
            var classList = element.classList;
            if(opensubs.length !=0) {
                    for(var i = 0; i < opensubs.length; i++){
                    opensubs[i].classList.remove('open');
                }
            } 
                classList.add('open');

        });
    }
    }
$(function(){
		var tree = $("ul.tree");
    $.each(json.category,function(category){
    	var categoryValue = json.category[category];
    	tree.append('<li><a href="#">'+categoryValue.title+'</a><ul></ul></li>');
      var el = tree.children("li").children("ul");
      $.each(categoryValue.items,function(itemId){
      	var item = categoryValue.items[itemId];
        $(el[category]).append('<li><a href="#">'+item.title+'</a></li>');
        if(item.thirditems){
        	$(el[category]).children("li").append('<ul></ul>');
          var el1 = $(el[category]).children("li").children("ul");
          $.each(item.thirditems,function(thirdItemId){
            var thirdItem = item.thirditems[thirdItemId];
            
           $(el1[itemId]).append('<li><a href="#">'+thirdItem.title+'</a><ul></ul></li>');
          });
        }
       
      });
    });
    expander();
});
body {
    font-family: Arial;
}

ul.tree li {
    list-style-type: none;
    position: relative;
}

ul.tree li ul {
    display: none;
}

ul.tree li.open > ul {
    display: block;
}

ul.tree li a {
    color: black;
    text-decoration: none;
}

ul.tree li a:before {
    height: 1em;
    padding:0 .1em;
    font-size: .8em;
    display: block;
    position: absolute;
    left: -1.3em;
    top: .2em;
}

ul.tree li > a:not(:last-child):before {
    content: '+';
}

ul.tree li.open > a:not(:last-child):before {
    content: '-';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="tree"></ul>
var el1 = el.children("li").children("ul");
var el1 = $(el[category]).children("li").children("ul");
Recursively add property to every node in a tree-like structure and return modified tree

Recursively add property to every node in a tree-like structure and return modified tree


By : user898710
Date : March 29 2020, 07:55 AM
Any of those help It gets more easy if you seperate the code into multiple functions and use the cool async / await syntax. Furst define an async function that updates one node without caring for the children:
code :
async function updateNode(node) {
 const [votedata, uservote] = await Promise.all([
   axios.get('/api/comment/'+root.id+'/votes'),
    axios.get('/api/votes/comment/'+root.id+'/'+Auth.getToken(), { headers: Auth.getApiAuthHeader() })
 ]);

 node.totalVotes = votedata.total;
 node.instance = 'comment';

 if(uservote)
   node.userVote = uservote;
}
async function updateNodeRecursively(node) {
  await updateNode(node);
  await Promise.all(node.children.map(updateNodeRecursively));
}
Related Posts Related Posts :
  • Why does C# also not allow empty conditions in while loops?
  • Unable to get a block of code into my regex match groups
  • What is difference between dbcontext.Add and dbcontext.AddObject
  • How do I update the file version number of C# DLL without recompiling?
  • Value for html control always null
  • HttpClient hangs when timeout is setting (Windows Phone)
  • Handle Multiple Form tag in asp.net page?
  • create word document with html content in c#
  • Confusion about Find And Replace
  • Format sms messages in Clickatell
  • Automated Function Overload
  • String to date in MS Access SQL statement gives type mismatch error
  • ShowDialog exiting on certain events
  • Is there a try Convert.ToInt32... avoiding exceptions
  • How to move wpf application into minimize tray at Window Start-up C#?
  • How to change display format of long variable?
  • How to use Addfields in MongoDB C# Aggregation Pipeline
  • MsTest TestCleanup method not called when an unhandled exception is thrown
  • missing last data when exporting gridview to excel
  • How to add array of objects to List in c#
  • Lambda Expression to order (sort) my list collection
  • Library for displaying music notation
  • How to compare two dictionaries in c# and get the output as True and False after validation
  • specify fields to be serialized with JSON
  • How do you obtain the content of a specific node using XmlDocument in C#?
  • How to ignore the first line in a csv file when you read the csv file in C#
  • c# - Problem calling public void from class
  • How to tell a class which objects it should create? Type vs. object confusion :(
  • Save CheckBox state to xml
  • WIX CAQuietExec NETSH Command Fails
  • Issues sending http put request every 60 seconds to RoR app
  • ConfigurationManager.ConnectionStrings.ConnectionString Issue
  • Real size WPF controls for printing
  • How to cancel properly?
  • C# String multiplication error
  • Using Solrnet and Assigning Attributes with Entity Framework Generated POCOs
  • Regex pattern for single backslash
  • TextBox: insert spaces for credit card number?
  • C# DLL loaded for exe-application is not found when launching similar DLL by rundll32.exe
  • Debug a Windows Service with WCF library
  • Open a file from an external assembly?
  • Servicestack RegistrationFeature Unable to bind request
  • Index was outside the bounds of the array confusion
  • Error in Xml to List code. The ':' character, hexadecimal value 0x3A, cannot be included in a name
  • I am trying to do a while loop with a string conditional statement in C#
  • C# 'Cannot access a disposed object. Object name: 'SslStream'.'
  • How to make Gecko use seperate CookieContainer per instance?
  • C# Advanced form "please wait"
  • Send and Receive data C# using network stream
  • How to discover that appsettings changed in C#?
  • Check what needs full trust
  • What is the execution order of an MVC Razor view/layout
  • Table designer (Entity Framework) is too resource intense
  • How to clean up an exception string so it can be displayed via Javascript Alert?
  • Configuring Amazon SES Feedback Notifications via Amazon SNS in ASP.NET MVC (C#)
  • C# api responce and request
  • Dynamodb putitem function not working properly
  • theme in windows phone(light or dark) using c#
  • Backup attached database file(.mdf) using c# and SQL Server
  • What is 'TextFile' and where it is uses in WPF project
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org